home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c-part2 / 12979 < prev    next >
Encoding:
Text File  |  1996-08-05  |  252.3 KB  |  6,604 lines

  1. Newsgroups: comp.lang.c,comp.lang.c.moderated,comp.answers,news.answers
  2. Path: new-news.sprintlink.net!eskimo!scs
  3. From: scs@eskimo.com (Steve Summit)
  4. Subject: comp.lang.c Answers to Frequently Asked Questions (FAQ List)
  5. X-Nntp-Posting-Host: eskimo.com
  6. Message-ID: <1996Apr03.1143.scs.0001@eskimo.com>
  7. Followup-To: poster
  8. Originator: scs@eskimo.com
  9. Sender: news@eskimo.com (News User Id)
  10. Supersedes: <1996Mar01.0300.scs.0001@eskimo.com>
  11. Reply-To: scs@eskimo.com
  12. X-Pgp-Signature: Version: 2.6
  13.     iQCSAwUBMWLTL96sm4I1rmP1AQEogQPkD0GEIUv9OzMOfvpeIQRGOZLDY6oE6HZI
  14.     ab52RDgZWV75lgFoWERED2t8s3Lf8O7sQg2IRP3ZbQslreUI6/Y3r8ACRuuxnS4H
  15.     lLbf6IUm+F6i/8m8vBRLSiN/4FyZUjombb6bG3VHkCAtFdGz7C08kqCGguVp39oj
  16.     6BWHkG8=
  17.     =BCff
  18. X-Archive-Name: C-faq/faq
  19. Organization: only when absolutely necessary
  20. X-Version: 3.3
  21. Date: Wed, 3 Apr 1996 19:45:40 GMT
  22. X-Last-Modified: April 3, 1996
  23. Approved: news-answers-request@MIT.Edu
  24. Expires: Fri, 3 May 1996 00:00:00 GMT
  25. X-Url: http://www.eskimo.com/~scs/C-faq/top.html
  26.  
  27. Archive-name: C-faq/faq
  28. Comp-lang-c-archive-name: C-FAQ-list
  29. URL: http://www.eskimo.com/~scs/C-faq/top.html
  30.  
  31. [Last modified April 3, 1996 by scs.]
  32.  
  33. This article is Copyright 1990-1996 by Steve Summit.  Content from the
  34. book _C Programming FAQs: Frequently Asked Questions_ is made available
  35. here by permission of the author and the publisher as a service to the
  36. community.  It is intended to complement the use of the published text
  37. and is protected by international copyright laws.  The content is made
  38. available here and may be accessed freely for personal use but may not
  39. be republished without permission.
  40.  
  41. Certain topics come up again and again on this newsgroup.  They are good
  42. questions, and the answers may not be immediately obvious, but each time
  43. they recur, much net bandwidth and reader time is wasted on repetitive
  44. responses, and on tedious corrections to the incorrect answers which are
  45. inevitably posted.
  46.  
  47. This article, which is posted monthly, attempts to answer these common
  48. questions definitively and succinctly, so that net discussion can move
  49. on to more constructive topics without continual regression to first
  50. principles.
  51.  
  52. No mere newsgroup article can substitute for thoughtful perusal of a
  53. full-length tutorial or language reference manual.  Anyone interested
  54. enough in C to be following this newsgroup should also be interested
  55. enough to read and study one or more such manuals, preferably several
  56. times.  Some C books and compiler manuals are unfortunately inadequate;
  57. a few even perpetuate some of the myths which this article attempts to
  58. refute.  Several noteworthy books on C are listed in this article's
  59. bibliography; see also question 18.10.  Many of the questions and
  60. answers are cross-referenced to these books, for further study by the
  61. interested and dedicated reader (but beware of ANSI vs. ISO C Standard
  62. section numbers; see question 11.1).
  63.  
  64. If you have a question about C which is not answered in this article,
  65. first try to answer it by checking a few of the referenced books, or by
  66. asking knowledgeable colleagues, before posing your question to the net
  67. at large.  There are many people on the net who are happy to answer
  68. questions, but the volume of repetitive answers posted to one question,
  69. as well as the growing number of questions as the net attracts more
  70. readers, can become oppressive.  If you have questions or comments
  71. prompted by this article, please reply by mail rather than following up --
  72. this article is meant to decrease net traffic, not increase it.
  73.  
  74. Besides listing frequently-asked questions, this article also summarizes
  75. frequently-posted answers.  Even if you know all the answers, it's worth
  76. skimming through this list once in a while, so that when you see one of
  77. its questions unwittingly posted, you won't have to waste time
  78. answering.
  79.  
  80. This article was last modified on April 3, 1996, and its travels
  81. may have taken it far from its original home on Usenet.  It may now
  82. be out-of-date, particularly if you are looking at a printed copy or one
  83. retrieved from a tertiary archive site or CD-ROM.  You can always obtain
  84. the most up-to-date copy by anonymous ftp from sites ftp.eskimo.com,
  85. rtfm.mit.edu, or ftp.uu.net (see questions 18.16 and 20.40), or by
  86. sending the e-mail message "help" to mail-server@rtfm.mit.edu .  Since
  87. this list is modified from time to time, its question numbers may not
  88. match those in older or newer copies which are in circulation; be
  89. careful when referring to FAQ list entries by number alone.
  90.  
  91. This article was produced for free redistribution.  You should not need
  92. to pay anyone for a copy of it.
  93.  
  94. Other versions of this document are also available.  Posted along with
  95. it are an abridged version and (when there are changes) a list of
  96. differences with respect to the previous version.  A
  97. hypertext version is available on the world-wide web (WWW); see URL
  98. http://www.eskimo.com/~scs/C-faq/top.html .  Finally, for those who
  99. might prefer a bound, hardcopy version (and even longer answers to even
  100. more questions!), a book-length version has been published by Addison-
  101. Wesley (ISBN 0-201-84519-9).
  102.  
  103. This article is always being improved.  Your input is welcomed.  Send
  104. your comments to scs@eskimo.com .
  105.  
  106. The questions answered here are divided into several categories:
  107.  
  108.      1. Declarations and Initializations
  109.      2. Structures, Unions, and Enumerations
  110.      3. Expressions
  111.      4. Pointers
  112.      5. Null Pointers
  113.      6. Arrays and Pointers
  114.      7. Memory Allocation
  115.      8. Characters and Strings
  116.      9. Boolean Expressions and Variables
  117.     10. C Preprocessor
  118.     11. ANSI/ISO Standard C
  119.     12. Stdio
  120.     13. Library Functions
  121.     14. Floating Point
  122.     15. Variable-Length Argument Lists
  123.     16. Strange Problems
  124.     17. Style
  125.     18. Tools and Resources
  126.     19. System Dependencies
  127.     20. Miscellaneous
  128.  
  129. (The question numbers within each section are not continuous because
  130. they are aligned with the forthcoming book-length version, which
  131. contains even more questions.)
  132.  
  133. Herewith, some frequently-asked questions and their answers:
  134.  
  135.  
  136. Section 1. Declarations and Initializations
  137.  
  138. 1.1:    How do you decide which integer type to use?
  139.  
  140. A:    If you might need large values (above 32,767 or below -32,767),
  141.     use long.  Otherwise, if space is very important (i.e. if there
  142.     are large arrays or many structures), use short.  Otherwise, use
  143.     int.  If well-defined overflow characteristics are important and
  144.     negative values are not, or if you want to steer clear of sign-
  145.     extension problems when manipulating bits or bytes, use one of
  146.     the corresponding unsigned types.  (Beware when mixing signed
  147.     and unsigned values in expressions, though.)
  148.  
  149.     Although character types (especially unsigned char) can be used
  150.     as "tiny" integers, doing so is sometimes more trouble than it's
  151.     worth, due to unpredictable sign extension and increased code
  152.     size.  (Using unsigned char can help; see question 12.1 for a
  153.     related problem.)
  154.  
  155.     A similar space/time tradeoff applies when deciding between
  156.     float and double.  None of the above rules apply if the address
  157.     of a variable is taken and must have a particular type.
  158.  
  159.     If for some reason you need to declare something with an *exact*
  160.     size (usually the only good reason for doing so is when
  161.     attempting to conform to some externally-imposed storage layout,
  162.     but see question 20.5), be sure to encapsulate the choice behind
  163.     an appropriate typedef.
  164.  
  165.     References: K&R1 Sec. 2.2 p. 34; K&R2 Sec. 2.2 p. 36, Sec. A4.2
  166.     pp. 195-6, Sec. B11 p. 257; ANSI Sec. 2.2.4.2.1, Sec. 3.1.2.5;
  167.     ISO Sec. 5.2.4.2.1, Sec. 6.1.2.5; H&S Secs. 5.1,5.2 pp. 110-114.
  168.  
  169. 1.4:    What should the 64-bit type on new, 64-bit machines be?
  170.  
  171. A:    Some vendors of C products for 64-bit machines support 64-bit
  172.     long ints.  Others fear that too much existing code is written
  173.     to assume that ints and longs are the same size, or that one or
  174.     the other of them is exactly 32 bits, and introduce a new,
  175.     nonstandard, 64-bit long long (or __longlong) type instead.
  176.  
  177.     Programmers interested in writing portable code should therefore
  178.     insulate their 64-bit type needs behind appropriate typedefs.
  179.     Vendors who feel compelled to introduce a new, longer integral
  180.     type should advertise it as being "at least 64 bits" (which is
  181.     truly new, a type traditional C does not have), and not "exactly
  182.     64 bits."
  183.  
  184.     References: ANSI Sec. F.5.6; ISO Sec. G.5.6.
  185.  
  186. 1.7:    What's the best way to declare and define global variables?
  187.  
  188. A:    First, though there can be many "declarations" (and in many
  189.     translation units) of a single "global" (strictly speaking,
  190.     "external") variable or function, there must be exactly one
  191.     "definition".  (The definition is the declaration that actually
  192.     allocates space, and provides an initialization value, if any.)
  193.     The best arrangement is to place each definition in some
  194.     relevant .c file, with an external declaration in a header
  195.     (".h") file, which is #included wherever the declaration is
  196.     needed.  The .c file containing the definition should also
  197.     #include the same header file, so that the compiler can check
  198.     that the definition matches the declarations.
  199.  
  200.     This rule promotes a high degree of portability: it is
  201.     consistent with the requirements of the ANSI C Standard, and is
  202.     also consistent with most pre-ANSI compilers and linkers.  (Unix
  203.     compilers and linkers typically use a "common model" which
  204.     allows multiple definitions, as long as at most one is
  205.     initialized; this behavior is mentioned as a "common extension"
  206.     by the ANSI Standard, no pun intended.  A few very odd systems
  207.     may require an explicit initializer to distinguish a definition
  208.     from an external declaration.)
  209.  
  210.     It is possible to use preprocessor tricks to arrange that a line
  211.     like
  212.  
  213.         DEFINE(int, i);
  214.  
  215.     need only be entered once in one header file, and turned into a
  216.     definition or a declaration depending on the setting of some
  217.     macro, but it's not clear if this is worth the trouble.
  218.  
  219.     It's especially important to put global declarations in header
  220.     files if you want the compiler to catch inconsistent
  221.     declarations for you.  In particular, never place a prototype
  222.     for an external function in a .c file: it wouldn't generally be
  223.     checked for consistency with the definition, and an incompatible
  224.     prototype is worse than useless.
  225.  
  226.     See also questions 10.6 and 18.8.
  227.  
  228.     References: K&R1 Sec. 4.5 pp. 76-7; K&R2 Sec. 4.4 pp. 80-1; ANSI
  229.     Sec. 3.1.2.2, Sec. 3.7, Sec. 3.7.2, Sec. F.5.11; ISO
  230.     Sec. 6.1.2.2, Sec. 6.7, Sec. 6.7.2, Sec. G.5.11; Rationale
  231.     Sec. 3.1.2.2; H&S Sec. 4.8 pp. 101-104, Sec. 9.2.3 p. 267; CT&P
  232.     Sec. 4.2 pp. 54-56.
  233.  
  234. 1.11:    What does extern mean in a function declaration?
  235.  
  236. A:    It can be used as a stylistic hint to indicate that the
  237.     function's definition is probably in another source file, but
  238.     there is no formal difference between
  239.  
  240.         extern int f();
  241.  
  242.     and
  243.  
  244.         int f();
  245.  
  246.     References: ANSI Sec. 3.1.2.2, Sec. 3.5.1; ISO Sec. 6.1.2.2,
  247.     Sec. 6.5.1; Rationale Sec. 3.1.2.2; H&S Secs. 4.3,4.3.1 pp. 75-
  248.     6.
  249.  
  250. 1.12:    What's the auto keyword good for?
  251.  
  252. A:    Nothing; it's archaic.  See also question 20.37.
  253.  
  254.     References: K&R1 Sec. A8.1 p. 193; ANSI Sec. 3.1.2.4,
  255.     Sec. 3.5.1; ISO Sec. 6.1.2.4, Sec. 6.5.1; H&S Sec. 4.3 p. 75,
  256.     Sec. 4.3.1 p. 76.
  257.  
  258. 1.14:    I can't seem to define a linked list successfully.  I tried
  259.  
  260.         typedef struct {
  261.             char *item;
  262.             NODEPTR next;
  263.         } *NODEPTR;
  264.  
  265.     but the compiler gave me error messages.  Can't a structure in C
  266.     contain a pointer to itself?
  267.  
  268. A:    Structures in C can certainly contain pointers to themselves;
  269.     the discussion and example in section 6.5 of K&R make this
  270.     clear.  The problem with the NODEPTR example is that the typedef
  271.     has not been defined at the point where the "next" field is
  272.     declared.  To fix this code, first give the structure a tag
  273.     ("struct node").  Then, declare the "next" field as a simple
  274.     "struct node *", or disentangle the typedef declaration from the
  275.     structure definition, or both.  One corrected version would be
  276.  
  277.         struct node {
  278.             char *item;
  279.             struct node *next;
  280.         };
  281.  
  282.         typedef struct node *NODEPTR;
  283.  
  284.     and there are at least three other equivalently correct ways of
  285.     arranging it.
  286.  
  287.     A similar problem, with a similar solution, can arise when
  288.     attempting to declare a pair of typedef'ed mutually referential
  289.     structures.
  290.  
  291.     See also question 2.1.
  292.  
  293.     References: K&R1 Sec. 6.5 p. 101; K&R2 Sec. 6.5 p. 139; ANSI
  294.     Sec. 3.5.2, Sec. 3.5.2.3, esp. examples; ISO Sec. 6.5.2,
  295.     Sec. 6.5.2.3; H&S Sec. 5.6.1 pp. 132-3.
  296.  
  297. 1.21:    How do I declare an array of N pointers to functions returning
  298.     pointers to functions returning pointers to characters?
  299.  
  300. A:    The first part of this question can be answered in at least
  301.     three ways:
  302.  
  303.     1.  char *(*(*a[N])())();
  304.  
  305.     2.  Build the declaration up incrementally, using typedefs:
  306.  
  307.         typedef char *pc;    /* pointer to char */
  308.         typedef pc fpc();    /* function returning pointer to char */
  309.         typedef fpc *pfpc;    /* pointer to above */
  310.         typedef pfpc fpfpc();    /* function returning... */
  311.         typedef fpfpc *pfpfpc;    /* pointer to... */
  312.         pfpfpc a[N];        /* array of... */
  313.  
  314.     3.  Use the cdecl program, which turns English into C and vice
  315.         versa:
  316.  
  317.         cdecl> declare a as array of pointer to function returning
  318.             pointer to function returning pointer to char
  319.         char *(*(*a[])())()
  320.  
  321.         cdecl can also explain complicated declarations, help with
  322.         casts, and indicate which set of parentheses the arguments
  323.         go in (for complicated function definitions, like the one
  324.         above).  Versions of cdecl are in volume 14 of
  325.         comp.sources.unix (see question 18.16) and K&R2.
  326.  
  327.     Any good book on C should explain how to read these complicated
  328.     C declarations "inside out" to understand them ("declaration
  329.     mimics use").
  330.  
  331.     The pointer-to-function declarations in the examples above have
  332.     not included parameter type information.  When the parameters
  333.     have complicated types, declarations can *really* get messy.
  334.     (Modern versions of cdecl can help here, too.)
  335.  
  336.     References: K&R2 Sec. 5.12 p. 122; ANSI Sec. 3.5ff (esp.
  337.     Sec. 3.5.4); ISO Sec. 6.5ff (esp. Sec. 6.5.4); H&S Sec. 4.5 pp.
  338.     85-92, Sec. 5.10.1 pp. 149-50.
  339.  
  340. 1.22:    How can I declare a function that can return a pointer to a
  341.     function of the same type?  I'm building a state machine with
  342.     one function for each state, each of which returns a pointer to
  343.     the function for the next state.  But I can't find a way to
  344.     declare the functions.
  345.  
  346. A:    You can't quite do it directly.  Either have the function return
  347.     a generic function pointer, with some judicious casts to adjust
  348.     the types as the pointers are passed around; or have it return a
  349.     structure containing only a pointer to a function returning that
  350.     structure.
  351.  
  352. 1.25:    My compiler is complaining about an invalid redeclaration of a
  353.     function, but I only define it once and call it once.
  354.  
  355. A:    Functions which are called without a declaration in scope
  356.     (perhaps because the first call precedes the function's
  357.     definition) are assumed to be declared as returning int (and
  358.     without any argument type information), leading to discrepancies
  359.     if the function is later declared or defined otherwise.  Non-int
  360.     functions must be declared before they are called.
  361.  
  362.     Another possible source of this problem is that the function has
  363.     the same name as another one declared in some header file.
  364.  
  365.     See also questions 11.3 and 15.1.
  366.  
  367.     References: K&R1 Sec. 4.2 p. 70; K&R2 Sec. 4.2 p. 72; ANSI
  368.     Sec. 3.3.2.2; ISO Sec. 6.3.2.2; H&S Sec. 4.7 p. 101.
  369.  
  370. 1.30:    What can I safely assume about the initial values of variables
  371.     which are not explicitly initialized?  If global variables start
  372.     out as "zero," is that good enough for null pointers and
  373.     floating-point zeroes?
  374.  
  375. A:    Variables with "static" duration (that is, those declared
  376.     outside of functions, and those declared with the storage class
  377.     static), are guaranteed initialized (just once, at program
  378.     startup) to zero, as if the programmer had typed "= 0".
  379.     Therefore, such variables are initialized to the null pointer
  380.     (of the correct type; see also section 5) if they are pointers,
  381.     and to 0.0 if they are floating-point.
  382.  
  383.     Variables with "automatic" duration (i.e. local variables
  384.     without the static storage class) start out containing garbage,
  385.     unless they are explicitly initialized.  (Nothing useful can be
  386.     predicted about the garbage.)
  387.  
  388.     Dynamically-allocated memory obtained with malloc() and
  389.     realloc() is also likely to contain garbage, and must be
  390.     initialized by the calling program, as appropriate.  Memory
  391.     obtained with calloc() is all-bits-0, but this is not
  392.     necessarily useful for pointer or floating-point values (see
  393.     question 7.31, and section 5).
  394.  
  395.     References: K&R1 Sec. 4.9 pp. 82-4; K&R2 Sec. 4.9 pp. 85-86;
  396.     ANSI Sec. 3.5.7, Sec. 4.10.3.1, Sec. 4.10.5.3; ISO Sec. 6.5.7,
  397.     Sec. 7.10.3.1, Sec. 7.10.5.3; H&S Sec. 4.2.8 pp. 72-3, Sec. 4.6
  398.     pp. 92-3, Sec. 4.6.2 pp. 94-5, Sec. 4.6.3 p. 96, Sec. 16.1 p.
  399.     386.
  400.  
  401. 1.31:    This code, straight out of a book, isn't compiling:
  402.  
  403.         f()
  404.         {
  405.             char a[] = "Hello, world!";
  406.         }
  407.  
  408. A:    Perhaps you have a pre-ANSI compiler, which doesn't allow
  409.     initialization of "automatic aggregates" (i.e. non-static local
  410.     arrays, structures, and unions).  As a workaround, you can make
  411.     the array global or static (if you won't need a fresh copy
  412.     during any subsequent calls), or replace it with a pointer (if
  413.     the array won't be written to).  (You can always initialize
  414.     local char * variables to point to string literals, but see
  415.     question 1.32 below.)  If neither of these conditions hold,
  416.     you'll have to initialize the array by hand with strcpy() when
  417.     f() is called.  See also question 11.29.
  418.  
  419. 1.32:    What is the difference between these initializations?
  420.  
  421.         char a[] = "string literal";
  422.         char *p  = "string literal";
  423.  
  424.     My program crashes if I try to assign a new value to p[i].
  425.  
  426. A:    A string literal can be used in two slightly different ways.  As
  427.     an array initializer (as in the declaration of char a[]), it
  428.     specifies the initial values of the characters in that array.
  429.     Anywhere else, it turns into an unnamed, static array of
  430.     characters, which may be stored in read-only memory, which is
  431.     why you can't safely modify it.  In an expression context, the
  432.     array is converted at once to a pointer, as usual (see section
  433.     6), so the second declaration initializes p to point to the
  434.     unnamed array's first element.
  435.  
  436.     (For compiling old code, some compilers have a switch
  437.     controlling whether strings are writable or not.)
  438.  
  439.     See also questions 1.31, 6.1, 6.2, and 6.8.
  440.  
  441.     References: K&R2 Sec. 5.5 p. 104; ANSI Sec. 3.1.4, Sec. 3.5.7;
  442.     ISO Sec. 6.1.4, Sec. 6.5.7; Rationale Sec. 3.1.4; H&S Sec. 2.7.4
  443.     pp. 31-2.
  444.  
  445. 1.34:    I finally figured out the syntax for declaring pointers to
  446.     functions, but now how do I initialize one?
  447.  
  448. A:    Use something like
  449.  
  450.         extern int func();
  451.         int (*fp)() = func;
  452.  
  453.     When the name of a function appears in an expression like this,
  454.     it "decays" into a pointer (that is, it has its address
  455.     implicitly taken), much as an array name does.
  456.  
  457.     An explicit declaration for the function is normally needed,
  458.     since implicit external function declaration does not happen in
  459.     this case (because the function name in the initialization is
  460.     not part of a function call).
  461.  
  462.     See also question 4.12.
  463.  
  464.  
  465. Section 2. Structures, Unions, and Enumerations
  466.  
  467. 2.1:    What's the difference between these two declarations?
  468.  
  469.         struct x1 { ... };
  470.         typedef struct { ... } x2;
  471.  
  472. A:    The first form declares a "structure tag"; the second declares a
  473.     "typedef".  The main difference is that the second declaration
  474.     is of a slightly more abstract type -- its users don't
  475.     necessarily know that it is a structure, and the keyword struct
  476.     is not used when declaring instances of it.
  477.  
  478. 2.2:    Why doesn't
  479.  
  480.         struct x { ... };
  481.         x thestruct;
  482.  
  483.     work?
  484.  
  485. A:    C is not C++.  Typedef names are not automatically generated for
  486.     structure tags.  See also question 2.1 above.
  487.  
  488. 2.3:    Can a structure contain a pointer to itself?
  489.  
  490. A:    Most certainly.  See question 1.14.
  491.  
  492. 2.4:    What's the best way of implementing opaque (abstract) data types
  493.     in C?
  494.  
  495. A:    One good way is for clients to use structure pointers (perhaps
  496.     additionally hidden behind typedefs) which point to structure
  497.     types which are not publicly defined.
  498.  
  499. 2.6:    I came across some code that declared a structure like this:
  500.  
  501.         struct name {
  502.             int namelen;
  503.             char namestr[1];
  504.         };
  505.  
  506.     and then did some tricky allocation to make the namestr array
  507.     act like it had several elements.  Is this legal or portable?
  508.  
  509. A:    This technique is popular, although Dennis Ritchie has called it
  510.     "unwarranted chumminess with the C implementation."  An official
  511.     interpretation has deemed that it is not strictly conforming
  512.     with the C Standard.  (A thorough treatment of the arguments
  513.     surrounding the legality of the technique is beyond the scope of
  514.     this list.)  It does seem to be portable to all known
  515.     implementations.  (Compilers which check array bounds carefully
  516.     might issue warnings.)
  517.  
  518.     Another possibility is to declare the variable-size element very
  519.     large, rather than very small; in the case of the above example:
  520.  
  521.         ...
  522.         char namestr[MAXSIZE];
  523.         ...
  524.  
  525.     where MAXSIZE is larger than any name which will be stored.
  526.     However, it looks like this technique is disallowed by a strict
  527.     interpretation of the Standard as well.
  528.  
  529.     References: Rationale Sec. 3.5.4.2.
  530.  
  531. 2.7:    I heard that structures could be assigned to variables and
  532.     passed to and from functions, but K&R1 says not.
  533.  
  534. A:    What K&R1 said was that the restrictions on structure operations
  535.     would be lifted in a forthcoming version of the compiler, and in
  536.     fact structure assignment and passing were fully functional in
  537.     Ritchie's compiler even as K&R1 was being published.  Although a
  538.     few early C compilers lacked these operations, all modern
  539.     compilers support them, and they are part of the ANSI C
  540.     standard, so there should be no reluctance to use them.
  541.  
  542.     (Note that when a structure is assigned, passed, or returned,
  543.     the copying is done monolithically; anything pointed to by any
  544.     pointer fields is *not* copied.)
  545.  
  546.     References: K&R1 Sec. 6.2 p. 121; K&R2 Sec. 6.2 p. 129; ANSI
  547.     Sec. 3.1.2.5, Sec. 3.2.2.1, Sec. 3.3.16; ISO Sec. 6.1.2.5,
  548.     Sec. 6.2.2.1, Sec. 6.3.16; H&S Sec. 5.6.2 p. 133.
  549.  
  550. 2.8:    Why can't you compare structures?
  551.  
  552. A:    There is no single, good way for a compiler to implement
  553.     structure comparison which is consistent with C's low-level
  554.     flavor.  A simple byte-by-byte comparison could founder on
  555.     random bits present in unused "holes" in the structure (such
  556.     padding is used to keep the alignment of later fields correct;
  557.     see question 2.12).  A field-by-field comparison might require
  558.     unacceptable amounts of repetitive code for large structures.
  559.  
  560.     If you need to compare two structures, you'll have to write your
  561.     own function to do so, field by field.
  562.  
  563.     References: K&R2 Sec. 6.2 p. 129; ANSI Sec. 4.11.4.1 footnote
  564.     136; Rationale Sec. 3.3.9; H&S Sec. 5.6.2 p. 133.
  565.  
  566. 2.9:    How are structure passing and returning implemented?
  567.  
  568. A:    When structures are passed as arguments to functions, the entire
  569.     structure is typically pushed on the stack, using as many words
  570.     as are required.  (Programmers often choose to use pointers to
  571.     structures instead, precisely to avoid this overhead.)  Some
  572.     compilers merely pass a pointer to the structure, though they
  573.     may have to make a local copy to preserve pass-by-value
  574.     semantics.
  575.  
  576.     Structures are often returned from functions in a location
  577.     pointed to by an extra, compiler-supplied "hidden" argument to
  578.     the function.  Some older compilers used a special, static
  579.     location for structure returns, although this made structure-
  580.     valued functions non-reentrant, which ANSI C disallows.
  581.  
  582.     References: ANSI Sec. 2.2.3; ISO Sec. 5.2.3.
  583.  
  584. 2.10:    How can I pass constant values to functions which accept
  585.     structure arguments?
  586.  
  587. A:    C has no way of generating anonymous structure values.  You will
  588.     have to use a temporary structure variable or a little structure-
  589.     building function.  (gcc provides structure constants as an
  590.     extension, and the mechanism will probably be added to a future
  591.     revision of the C Standard.)  See also question 4.10.
  592.  
  593. 2.11:    How can I read/write structures from/to data files?
  594.  
  595. A:    It is relatively straightforward to write a structure out using
  596.     fwrite():
  597.  
  598.         fwrite(&somestruct, sizeof somestruct, 1, fp);
  599.  
  600.     and a corresponding fread invocation can read it back in.
  601.     (Under pre-ANSI C, a (char *) cast on the first argument is
  602.     required.  What's important is that fwrite() receive a byte
  603.     pointer, not a structure pointer.)  However, data files so
  604.     written will *not* be portable (see questions 2.12 and 20.5).
  605.     Note also that if the structure contains any pointers, only the
  606.     pointer values will be written, and they are most unlikely to be
  607.     valid when read back in.  Finally, note that for widespread
  608.     portability you must use the "b" flag when fopening the files;
  609.     see question 12.38.
  610.  
  611.     A more portable solution, though it's a bit more work initially,
  612.     is to write a pair of functions for writing and reading a
  613.     structure, field-by-field, in a portable (perhaps even human-
  614.     readable) way.
  615.  
  616.     References: H&S Sec. 15.13 p. 381.
  617.  
  618. 2.12:    My compiler is leaving holes in structures, which is wasting
  619.     space and preventing "binary" I/O to external data files.  Can I
  620.     turn off the padding, or otherwise control the alignment of
  621.     structure fields?
  622.  
  623. A:    Your compiler may provide an extension to give you this control
  624.     (perhaps a #pragma; see question 11.20), but there is no
  625.     standard method.
  626.  
  627.     See also question 20.5.
  628.  
  629.     References: K&R2 Sec. 6.4 p. 138; H&S Sec. 5.6.4 p. 135.
  630.  
  631. 2.13:    Why does sizeof report a larger size than I expect for a
  632.     structure type, as if there were padding at the end?
  633.  
  634. A:    Structures may have this padding (as well as internal padding),
  635.     if necessary, to ensure that alignment properties will be
  636.     preserved when an array of contiguous structures is allocated.
  637.     Even when the structure is not part of an array, the end padding
  638.     remains, so that sizeof can always return a consistent size.
  639.     See question 2.12 above.
  640.  
  641.     References: H&S Sec. 5.6.7 pp. 139-40.
  642.  
  643. 2.14:    How can I determine the byte offset of a field within a
  644.     structure?
  645.  
  646. A:    ANSI C defines the offsetof() macro, which should be used if
  647.     available; see <stddef.h>.  If you don't have it, one possible
  648.     implementation is
  649.  
  650.         #define offsetof(type, mem) ((size_t) \
  651.             ((char *)&((type *)0)->mem - (char *)(type *)0))
  652.  
  653.     This implementation is not 100% portable; some compilers may
  654.     legitimately refuse to accept it.
  655.  
  656.     See question 2.15 below for a usage hint.
  657.  
  658.     References: ANSI Sec. 4.1.5; ISO Sec. 7.1.6; Rationale
  659.     Sec. 3.5.4.2; H&S Sec. 11.1 pp. 292-3.
  660.  
  661. 2.15:    How can I access structure fields by name at run time?
  662.  
  663. A:    Build a table of names and offsets, using the offsetof() macro.
  664.     The offset of field b in struct a is
  665.  
  666.         offsetb = offsetof(struct a, b)
  667.  
  668.     If structp is a pointer to an instance of this structure, and
  669.     field b is an int (with offset as computed above), b's value can
  670.     be set indirectly with
  671.  
  672.         *(int *)((char *)structp + offsetb) = value;
  673.  
  674. 2.18:    This program works correctly, but it dumps core after it
  675.     finishes.  Why?
  676.  
  677.         struct list {
  678.             char *item;
  679.             struct list *next;
  680.         }
  681.  
  682.         /* Here is the main program. */
  683.  
  684.         main(argc, argv)
  685.         { ... }
  686.  
  687. A:    A missing semicolon causes main() to be declared as returning a
  688.     structure.  (The connection is hard to see because of the
  689.     intervening comment.)  Since structure-valued functions are
  690.     usually implemented by adding a hidden return pointer (see
  691.     question 2.9), the generated code for main() tries to accept
  692.     three arguments, although only two are passed (in this case, by
  693.     the C start-up code).  See also questions 10.9 and 16.4.
  694.  
  695.     References: CT&P Sec. 2.3 pp. 21-2.
  696.  
  697. 2.20:    Can I initialize unions?
  698.  
  699. A:    ANSI Standard C allows an initializer for the first member of a
  700.     union.  There is no standard way of initializing any other
  701.     member (nor, under a pre-ANSI compiler, is there generally any
  702.     way of initializing a union at all).
  703.  
  704.     References: K&R2 Sec. 6.8 pp. 148-9; ANSI Sec. 3.5.7; ISO
  705.     Sec. 6.5.7; H&S Sec. 4.6.7 p. 100.
  706.  
  707. 2.22:    What is the difference between an enumeration and a set of
  708.     preprocessor #defines?
  709.  
  710. A:    At the present time, there is little difference.  Although many
  711.     people might have wished otherwise, the C Standard says that
  712.     enumerations may be freely intermixed with other integral types,
  713.     without errors.  (If such intermixing were disallowed without
  714.     explicit casts, judicious use of enumerations could catch
  715.     certain programming errors.)
  716.  
  717.     Some advantages of enumerations are that the numeric values are
  718.     automatically assigned, that a debugger may be able to display
  719.     the symbolic values when enumeration variables are examined, and
  720.     that they obey block scope.  (A compiler may also generate
  721.     nonfatal warnings when enumerations and integers are
  722.     indiscriminately mixed, since doing so can still be considered
  723.     bad style even though it is not strictly illegal.)  A
  724.     disadvantage is that the programmer has little control over
  725.     those nonfatal warnings; some programmers also resent not having
  726.     control over the sizes of enumeration variables.
  727.  
  728.     References: K&R2 Sec. 2.3 p. 39, Sec. A4.2 p. 196; ANSI
  729.     Sec. 3.1.2.5, Sec. 3.5.2, Sec. 3.5.2.2, Appendix E; ISO
  730.     Sec. 6.1.2.5, Sec. 6.5.2, Sec. 6.5.2.2, Annex F; H&S Sec. 5.5
  731.     pp. 127-9, Sec. 5.11.2 p. 153.
  732.  
  733. 2.24:    Is there an easy way to print enumeration values symbolically?
  734.  
  735. A:    No.  You can write a little function to map an enumeration
  736.     constant to a string.  (If all you're worried about is
  737.     debugging, a good debugger should automatically print
  738.     enumeration constants symbolically.)
  739.  
  740.  
  741. Section 3. Expressions
  742.  
  743. 3.1:    Why doesn't this code:
  744.  
  745.         a[i] = i++;
  746.  
  747.     work?
  748.  
  749. A:    The subexpression i++ causes a side effect -- it modifies i's
  750.     value -- which leads to undefined behavior since i is also
  751.     referenced elsewhere in the same expression.  (Note that
  752.     although the language in K&R suggests that the behavior of this
  753.     expression is unspecified, the C Standard makes the stronger
  754.     statement that it is undefined -- see question 11.33.)
  755.  
  756.     References: K&R1 Sec. 2.12; K&R2 Sec. 2.12; ANSI Sec. 3.3; ISO
  757.     Sec. 6.3.
  758.  
  759. 3.2:    Under my compiler, the code
  760.  
  761.         int i = 7;
  762.         printf("%d\n", i++ * i++);
  763.  
  764.     prints 49.  Regardless of the order of evaluation, shouldn't it
  765.     print 56?
  766.  
  767. A:    Although the postincrement and postdecrement operators ++ and --
  768.     perform their operations after yielding the former value, the
  769.     implication of "after" is often misunderstood.  It is *not*
  770.     guaranteed that an increment or decrement is performed
  771.     immediately after giving up the previous value and before any
  772.     other part of the expression is evaluated.  It is merely
  773.     guaranteed that the update will be performed sometime before the
  774.     expression is considered "finished" (before the next "sequence
  775.     point," in ANSI C's terminology; see question 3.8).  In the
  776.     example, the compiler chose to multiply the previous value by
  777.     itself and to perform both increments afterwards.
  778.  
  779.     The behavior of code which contains multiple, ambiguous side
  780.     effects has always been undefined.  (Loosely speaking, by
  781.     "multiple, ambiguous side effects" we mean any combination of
  782.     ++, --, =, +=, -=, etc. in a single expression which causes the
  783.     same object either to be modified twice or modified and then
  784.     inspected.  This is a rough definition; see question 3.8 for a
  785.     precise one, and question 11.33 for the meaning of "undefined.")
  786.     Don't even try to find out how your compiler implements such
  787.     things (contrary to the ill-advised exercises in many C
  788.     textbooks); as K&R wisely point out, "if you don't know *how*
  789.     they are done on various machines, that innocence may help to
  790.     protect you."
  791.  
  792.     References: K&R1 Sec. 2.12 p. 50; K&R2 Sec. 2.12 p. 54; ANSI
  793.     Sec. 3.3; ISO Sec. 6.3; CT&P Sec. 3.7 p. 47; PCS Sec. 9.5 pp.
  794.     120-1.
  795.  
  796. 3.3:    I've experimented with the code
  797.  
  798.         [CENSORED]
  799.  
  800.     on several compilers.  Some gave i the value 3, some gave 4, but
  801.     one gave 7.  I know the behavior is undefined, but how could it
  802.     give 7?
  803.  
  804. A:    [I apologize for the censorship of the question, but the
  805.     expression that used to be there was indecent, and by the
  806.     newly-passed Communications Decency Act of the U.S., I am
  807.     prohibited from transmitting "indecent" material, whatever that
  808.     is.  Suffice it to say that the expression tried to modify the
  809.     same variable twice between sequence points.  --scs]
  810.  
  811.     Undefined behavior means *anything* can happen.  See questions
  812.     3.9 and 11.33.  (Also, note that neither i++ nor ++i is the same
  813.     as i+1.  If you want to increment i, use i=i+1 or i++ or ++i,
  814.     not some combination.  See also question 3.12.)
  815.  
  816. 3.4:    Can I use explicit parentheses to force the order of evaluation
  817.     I want?  Even if I don't, doesn't precedence dictate it?
  818.  
  819. A:    Not in general.
  820.  
  821.     Operator precedence and explicit parentheses impose only a
  822.     partial ordering on the evaluation of an expression.  In the
  823.     expression
  824.  
  825.         f() + g() * h()
  826.  
  827.     although we know that the multiplication will happen before the
  828.     addition, there is no telling which of the three functions will
  829.     be called first.
  830.  
  831.     When you need to ensure the order of subexpression evaluation,
  832.     you may need to use explicit temporary variables and separate
  833.     statements.
  834.  
  835.     References: K&R1 Sec. 2.12 p. 49, Sec. A.7 p. 185; K&R2
  836.     Sec. 2.12 pp. 52-3, Sec. A.7 p. 200.
  837.  
  838. 3.5:    But what about the && and || operators?
  839.     I see code like "while((c = getchar()) != EOF && c != '\n')" ...
  840.  
  841. A:    There is a special exception for those operators (as well as the
  842.     ?: operator): left-to-right evaluation is guaranteed (as is an
  843.     intermediate sequence point, see question 3.8).  Any book on C
  844.     should make this clear.
  845.  
  846.     References: K&R1 Sec. 2.6 p. 38, Secs. A7.11-12 pp. 190-1; K&R2
  847.     Sec. 2.6 p. 41, Secs. A7.14-15 pp. 207-8; ANSI Sec. 3.3.13,
  848.     Sec. 3.3.14, Sec. 3.3.15; ISO Sec. 6.3.13, Sec. 6.3.14,
  849.     Sec. 6.3.15; H&S Sec. 7.7 pp. 217-8, Sec. 7.8 pp. 218-20,
  850.     Sec. 7.12.1 p. 229; CT&P Sec. 3.7 pp. 46-7.
  851.  
  852. 3.8:    How can I understand these complex expressions?  What's a
  853.     "sequence point"?
  854.  
  855. A:    A sequence point is the point (at the end of a full expression,
  856.     or at the ||, &&, ?:, or comma operators, or just before a
  857.     function call) at which the dust has settled and all side
  858.     effects are guaranteed to be complete.  The ANSI/ISO C Standard
  859.     states that
  860.  
  861.         Between the previous and next sequence point an
  862.         object shall have its stored value modified at
  863.         most once by the evaluation of an expression.
  864.         Furthermore, the prior value shall be accessed
  865.         only to determine the value to be stored.
  866.  
  867.     The second sentence can be difficult to understand.  It says
  868.     that if an object is written to within a full expression, any
  869.     and all accesses to it within the same expression must be for
  870.     the purposes of computing the value to be written.  This rule
  871.     effectively constrains legal expressions to those in which the
  872.     accesses demonstrably precede the modification.
  873.  
  874.     See also question 3.9 below.
  875.  
  876.     References: ANSI Sec. 2.1.2.3, Sec. 3.3, Appendix B; ISO
  877.     Sec. 5.1.2.3, Sec. 6.3, Annex C; Rationale Sec. 2.1.2.3; H&S
  878.     Sec. 7.12.1 pp. 228-9.
  879.  
  880. 3.9:    So given
  881.  
  882.         a[i] = i++;
  883.  
  884.     we don't know which cell of a[] gets written to, but i does get
  885.     incremented by one.
  886.  
  887. A:    *No.*  Once an expression or program becomes undefined, *all*
  888.     aspects of it become undefined.  See questions 3.2, 3.3, 11.33,
  889.     and 11.35.
  890.  
  891. 3.12:    If I'm not using the value of the expression, should I use i++
  892.     or ++i to increment a variable?
  893.  
  894. A:    Since the two forms differ only in the value yielded, they are
  895.     entirely equivalent when only their side effect is needed.
  896.  
  897.     See also question 3.3.
  898.  
  899.     References: K&R1 Sec. 2.8 p. 43; K&R2 Sec. 2.8 p. 47; ANSI
  900.     Sec. 3.3.2.4, Sec. 3.3.3.1; ISO Sec. 6.3.2.4, Sec. 6.3.3.1; H&S
  901.     Sec. 7.4.4 pp. 192-3, Sec. 7.5.8 pp. 199-200.
  902.  
  903.  
  904. 3.14:    Why doesn't the code
  905.  
  906.         int a = 1000, b = 1000;
  907.         long int c = a * b;
  908.  
  909.     work?
  910.  
  911. A:    Under C's integral promotion rules, the multiplication is
  912.     carried out using int arithmetic, and the result may overflow or
  913.     be truncated before being promoted and assigned to the long int
  914.     left-hand side.  Use an explicit cast to force long arithmetic:
  915.  
  916.         long int c = (long int)a * b;
  917.  
  918.     Note that (long int)(a * b) would *not* have the desired effect.
  919.  
  920.     A similar problem can arise when two integers are divided, with
  921.     the result assigned to a floating-point variable.
  922.  
  923.     References: K&R1 Sec. 2.7 p. 41; K&R2 Sec. 2.7 p. 44; ANSI
  924.     Sec. 3.2.1.5; ISO Sec. 6.2.1.5; H&S Sec. 6.3.4 p. 176; CT&P
  925.     Sec. 3.9 pp. 49-50.
  926.  
  927. 3.16:    I have a complicated expression which I have to assign to one of
  928.     two variables, depending on a condition.  Can I use code like
  929.     this?
  930.  
  931.         ((condition) ? a : b) = complicated_expression;
  932.  
  933. A:    No.  The ?: operator, like most operators, yields a value, and
  934.     you can't assign to a value.  (In other words, ?: does not yield
  935.     an "lvalue".)  If you really want to, you can try something like
  936.  
  937.         *((condition) ? &a : &b) = complicated_expression;
  938.  
  939.     although this is admittedly not as pretty.
  940.  
  941.     References: ANSI Sec. 3.3.15 esp. footnote 50; ISO Sec. 6.3.15;
  942.     H&S Sec. 7.1 pp. 179-180.
  943.  
  944.  
  945. Section 4. Pointers
  946.  
  947. 4.2:    I'm trying to declare a pointer and allocate some space for it,
  948.     but it's not working.  What's wrong with this code?
  949.  
  950.         char *p;
  951.         *p = malloc(10);
  952.  
  953. A:    The pointer you declared is p, not *p.  To make a pointer point
  954.     somewhere, you just use the name of the pointer:
  955.  
  956.         p = malloc(10);
  957.  
  958.     It's when you're manipulating the pointed-to memory that you use
  959.     * as an indirection operator:
  960.  
  961.         *p = 'H';
  962.  
  963.     See also questions 1.21, 7.1, and 8.3.
  964.  
  965.     References: CT&P Sec. 3.1 p. 28.
  966.  
  967. 4.3:    Does *p++ increment p, or what it points to?
  968.  
  969. A:    Unary operators like *, ++, and -- all associate (group) from
  970.     right to left.  Therefore, *p++ increments p (and returns the
  971.     value pointed to by p before the increment).  To increment the
  972.     value pointed to by p, use (*p)++ (or perhaps ++*p, if the order
  973.     of the side effect doesn't matter).
  974.  
  975.     References: K&R1 Sec. 5.1 p. 91; K&R2 Sec. 5.1 p. 95; ANSI
  976.     Sec. 3.3.2, Sec. 3.3.3; ISO Sec. 6.3.2, Sec. 6.3.3; H&S
  977.     Sec. 7.4.4 pp. 192-3, Sec. 7.5 p. 193, Secs. 7.5.7,7.5.8 pp. 199-
  978.     200.
  979.  
  980. 4.5:    I have a char * pointer that happens to point to some ints, and
  981.     I want to step it over them.  Why doesn't
  982.  
  983.         ((int *)p)++;
  984.  
  985.     work?
  986.  
  987. A:    In C, a cast operator does not mean "pretend these bits have a
  988.     different type, and treat them accordingly"; it is a conversion
  989.     operator, and by definition it yields an rvalue, which cannot be
  990.     assigned to, or incremented with ++.  (It is an anomaly in pcc-
  991.     derived compilers, and an extension in gcc, that expressions
  992.     such as the above are ever accepted.)  Say what you mean: use
  993.  
  994.         p = (char *)((int *)p + 1);
  995.  
  996.     or (since p is a char *) simply
  997.  
  998.         p += sizeof(int);
  999.  
  1000.     Whenever possible, you should choose appropriate pointer types
  1001.     in the first place, instead of trying to treat one type as
  1002.     another.
  1003.  
  1004.     References: K&R2 Sec. A7.5 p. 205; ANSI Sec. 3.3.4 (esp.
  1005.     footnote 14); ISO Sec. 6.3.4; Rationale Sec. 3.3.2.4; H&S
  1006.     Sec. 7.1 pp. 179-80.
  1007.  
  1008. 4.8:    I have a function which accepts, and is supposed to initialize,
  1009.     a pointer:
  1010.  
  1011.         void f(ip)
  1012.         int *ip;
  1013.         {
  1014.             static int dummy = 5;
  1015.             ip = &dummy;
  1016.         }
  1017.  
  1018.     But when I call it like this:
  1019.  
  1020.         int *ip;
  1021.         f(ip);
  1022.  
  1023.     the pointer in the caller remains unchanged.
  1024.  
  1025. A:    Are you sure the function initialized what you thought it did?
  1026.     Remember that arguments in C are passed by value.  The called
  1027.     function altered only the passed copy of the pointer.  You'll
  1028.     either want to pass the address of the pointer (the function
  1029.     will end up accepting a pointer-to-a-pointer), or have the
  1030.     function return the pointer.
  1031.  
  1032.     See also questions 4.9 and 4.11.
  1033.  
  1034.  
  1035. 4.9:    Can I use a void ** pointer to pass a generic pointer to a
  1036.     function by reference?
  1037.  
  1038. A:    Not portably.  There is no generic pointer-to-pointer type in C.
  1039.     void * acts as a generic pointer only because conversions are
  1040.     applied automatically when other pointer types are assigned to
  1041.     and from void *'s; these conversions cannot be performed (the
  1042.     correct underlying pointer type is not known) if an attempt is
  1043.     made to indirect upon a void ** value which points at something
  1044.     other than a void *.
  1045.  
  1046. 4.10:    I have a function
  1047.  
  1048.         extern int f(int *);
  1049.  
  1050.     which accepts a pointer to an int.  How can I pass a constant by
  1051.     reference?  A call like
  1052.  
  1053.         f(&5);
  1054.  
  1055.     doesn't seem to work.
  1056.  
  1057. A:    You can't do this directly.  You will have to declare a
  1058.     temporary variable, and then pass its address to the function:
  1059.  
  1060.         int five = 5;
  1061.         f(&five);
  1062.  
  1063.     See also questions 2.10, 4.8, and 20.1.
  1064.  
  1065. 4.11:    Does C even have "pass by reference"?
  1066.  
  1067. A:    Not really.  Strictly speaking, C always uses pass by value.
  1068.     You can simulate pass by reference yourself, by defining
  1069.     functions which accept pointers and then using the & operator
  1070.     when calling, and the compiler will essentially simulate it for
  1071.     you when you pass an array to a function (by passing a pointer
  1072.     instead, see question 6.4 et al.), but C has nothing truly
  1073.     equivalent to formal pass by reference or C++ reference
  1074.     parameters.  (However, function-like preprocessor macros do
  1075.     provide a form of "call by name".)
  1076.  
  1077.     See also questions 4.8 and 20.1.
  1078.  
  1079.     References: K&R1 Sec. 1.8 pp. 24-5, Sec. 5.2 pp. 91-3; K&R2
  1080.     Sec. 1.8 pp. 27-8, Sec. 5.2 pp. 91-3; ANSI Sec. 3.3.2.2, esp.
  1081.     footnote 39; ISO Sec. 6.3.2.2; H&S Sec. 9.5 pp. 273-4.
  1082.  
  1083. 4.12:    I've seen different methods used for calling functions via
  1084.     pointers.  What's the story?
  1085.  
  1086. A:    Originally, a pointer to a function had to be "turned into" a
  1087.     "real" function, with the * operator (and an extra pair of
  1088.     parentheses, to keep the precedence straight), before calling:
  1089.  
  1090.         int r, func(), (*fp)() = func;
  1091.         r = (*fp)();
  1092.  
  1093.  
  1094.     It can also be argued that functions are always called via
  1095.     pointers, and that "real" function names always decay implicitly
  1096.     into pointers (in expressions, as they do in initializations;
  1097.     see question 1.34).  This reasoning, made widespread through pcc
  1098.     and adopted in the ANSI standard, means that
  1099.  
  1100.  
  1101.         r = fp();
  1102.  
  1103.     is legal and works correctly, whether fp is the name of a
  1104.     function or a pointer to one.  (The usage has always been
  1105.     unambiguous; there is nothing you ever could have done with a
  1106.     function pointer followed by an argument list except call the
  1107.     function pointed to.)  An explicit * is still allowed (and
  1108.     recommended, if portability to older compilers is important).
  1109.  
  1110.     See also question 1.34.
  1111.  
  1112.     References: K&R1 Sec. 5.12 p. 116; K&R2 Sec. 5.11 p. 120; ANSI
  1113.     Sec. 3.3.2.2; ISO Sec. 6.3.2.2; Rationale Sec. 3.3.2.2; H&S
  1114.     Sec. 5.8 p. 147, Sec. 7.4.3 p. 190.
  1115.  
  1116.  
  1117. Section 5. Null Pointers
  1118.  
  1119. 5.1:    What is this infamous null pointer, anyway?
  1120.  
  1121. A:    The language definition states that for each pointer type, there
  1122.     is a special value -- the "null pointer" -- which is
  1123.     distinguishable from all other pointer values and which is
  1124.     "guaranteed to compare unequal to a pointer to any object or
  1125.     function."  That is, the address-of operator & will never yield
  1126.     a null pointer, nor will a successful call to malloc().
  1127.     (malloc() does return a null pointer when it fails, and this is
  1128.     a typical use of null pointers: as a "special" pointer value
  1129.     with some other meaning, usually "not allocated" or "not
  1130.     pointing anywhere yet.")
  1131.  
  1132.     A null pointer is conceptually different from an uninitialized
  1133.     pointer.  A null pointer is known not to point to any object or
  1134.     function; an uninitialized pointer might point anywhere.  See
  1135.     also questions 1.30, 7.1, and 7.31.
  1136.  
  1137.     As mentioned above, there is a null pointer for each pointer
  1138.     type, and the internal values of null pointers for different
  1139.     types may be different.  Although programmers need not know the
  1140.     internal values, the compiler must always be informed which type
  1141.     of null pointer is required, so that it can make the distinction
  1142.     if necessary (see questions 5.2, 5.5, and 5.6 below).
  1143.  
  1144.     References: K&R1 Sec. 5.4 pp. 97-8; K&R2 Sec. 5.4 p. 102; ANSI
  1145.     Sec. 3.2.2.3; ISO Sec. 6.2.2.3; Rationale Sec. 3.2.2.3; H&S
  1146.     Sec. 5.3.2 pp. 121-3.
  1147.  
  1148. 5.2:    How do I get a null pointer in my programs?
  1149.  
  1150. A:    According to the language definition, a constant 0 in a pointer
  1151.     context is converted into a null pointer at compile time.  That
  1152.     is, in an initialization, assignment, or comparison when one
  1153.     side is a variable or expression of pointer type, the compiler
  1154.     can tell that a constant 0 on the other side requests a null
  1155.     pointer, and generate the correctly-typed null pointer value.
  1156.     Therefore, the following fragments are perfectly legal:
  1157.  
  1158.         char *p = 0;
  1159.         if(p != 0)
  1160.  
  1161.     (See also question 5.3.)
  1162.  
  1163.     However, an argument being passed to a function is not
  1164.     necessarily recognizable as a pointer context, and the compiler
  1165.     may not be able to tell that an unadorned 0 "means" a null
  1166.     pointer.  To generate a null pointer in a function call context,
  1167.     an explicit cast may be required, to force the 0 to be
  1168.     recognized as a pointer.  For example, the Unix system call
  1169.     execl takes a variable-length, null-pointer-terminated list of
  1170.     character pointer arguments, and is correctly called like this:
  1171.  
  1172.         execl("/bin/sh", "sh", "-c", "date", (char *)0);
  1173.  
  1174.     If the (char *) cast on the last argument were omitted, the
  1175.     compiler would not know to pass a null pointer, and would pass
  1176.     an integer 0 instead.  (Note that many Unix manuals get this
  1177.     example wrong .)
  1178.  
  1179.     When function prototypes are in scope, argument passing becomes
  1180.     an "assignment context," and most casts may safely be omitted,
  1181.     since the prototype tells the compiler that a pointer is
  1182.     required, and of which type, enabling it to correctly convert an
  1183.     unadorned 0.  Function prototypes cannot provide the types for
  1184.     variable arguments in variable-length argument lists however, so
  1185.     explicit casts are still required for those arguments.  (See
  1186.     also question 15.3.)  It is safest to properly cast all null
  1187.     pointer constants in function calls: to guard against varargs
  1188.     functions or those without prototypes, to allow interim use of
  1189.     non-ANSI compilers, and to demonstrate that you know what you
  1190.     are doing.  (Incidentally, it's also a simpler rule to
  1191.     remember.)
  1192.  
  1193.     Summary:
  1194.  
  1195.         Unadorned 0 okay:    Explicit cast required:
  1196.  
  1197.         initialization        function call,
  1198.                     no prototype in scope
  1199.         assignment
  1200.                     variable argument in
  1201.         comparison        varargs function call
  1202.  
  1203.         function call,
  1204.         prototype in scope,
  1205.         fixed argument
  1206.  
  1207.     References: K&R1 Sec. A7.7 p. 190, Sec. A7.14 p. 192; K&R2
  1208.     Sec. A7.10 p. 207, Sec. A7.17 p. 209; ANSI Sec. 3.2.2.3; ISO
  1209.     Sec. 6.2.2.3; H&S Sec. 4.6.3 p. 95, Sec. 6.2.7 p. 171.
  1210.  
  1211. 5.3:    Is the abbreviated pointer comparison "if(p)" to test for non-
  1212.     null pointers valid?  What if the internal representation for
  1213.     null pointers is nonzero?
  1214.  
  1215. A:    When C requires the Boolean value of an expression (in the if,
  1216.     while, for, and do statements, and with the &&, ||, !, and ?:
  1217.     operators), a false value is inferred when the expression
  1218.     compares equal to zero, and a true value otherwise.  That is,
  1219.     whenever one writes
  1220.  
  1221.         if(expr)
  1222.  
  1223.     where "expr" is any expression at all, the compiler essentially
  1224.     acts as if it had been written as
  1225.  
  1226.         if((expr) != 0)
  1227.  
  1228.     Substituting the trivial pointer expression "p" for "expr," we
  1229.     have
  1230.  
  1231.         if(p)    is equivalent to        if(p != 0)
  1232.  
  1233.     and this is a comparison context, so the compiler can tell that
  1234.     the (implicit) 0 is actually a null pointer constant, and use
  1235.     the correct null pointer value.  There is no trickery involved
  1236.     here; compilers do work this way, and generate identical code
  1237.     for both constructs.  The internal representation of a null
  1238.     pointer does *not* matter.
  1239.  
  1240.     The boolean negation operator, !, can be described as follows:
  1241.  
  1242.         !expr    is essentially equivalent to    (expr)?0:1
  1243.             or to                ((expr) == 0)
  1244.  
  1245.     which leads to the conclusion that
  1246.  
  1247.         if(!p)    is equivalent to        if(p == 0)
  1248.  
  1249.     "Abbreviations" such as if(p), though perfectly legal, are
  1250.     considered by some to be bad style (and by others to be good
  1251.     style; see question 17.10).
  1252.  
  1253.     See also question 9.2.
  1254.  
  1255.     References: K&R2 Sec. A7.4.7 p. 204; ANSI Sec. 3.3.3.3,
  1256.     Sec. 3.3.9, Sec. 3.3.13, Sec. 3.3.14, Sec. 3.3.15, Sec. 3.6.4.1,
  1257.     Sec. 3.6.5; ISO Sec. 6.3.3.3, Sec. 6.3.9, Sec. 6.3.13,
  1258.     Sec. 6.3.14, Sec. 6.3.15, Sec. 6.6.4.1, Sec. 6.6.5; H&S
  1259.     Sec. 5.3.2 p. 122.
  1260.  
  1261. 5.4:    What is NULL and how is it #defined?
  1262.  
  1263. A:    As a matter of style, many programmers prefer not to have
  1264.     unadorned 0's scattered through their programs.  Therefore, the
  1265.     preprocessor macro NULL is #defined (by <stdio.h> or <stddef.h>)
  1266.     with the value 0, possibly cast to (void *) (see also question
  1267.     5.6).  A programmer who wishes to make explicit the distinction
  1268.     between 0 the integer and 0 the null pointer constant can then
  1269.     use NULL whenever a null pointer is required.
  1270.  
  1271.     Using NULL is a stylistic convention only; the preprocessor
  1272.     turns NULL back into 0 which is then recognized by the compiler,
  1273.     in pointer contexts, as before.  In particular, a cast may still
  1274.     be necessary before NULL (as before 0) in a function call
  1275.     argument.  The table under question 5.2 above applies for NULL
  1276.     as well as 0 (an unadorned NULL is equivalent to an unadorned
  1277.     0).
  1278.  
  1279.     NULL should *only* be used for pointers; see question 5.9.
  1280.  
  1281.     References: K&R1 Sec. 5.4 pp. 97-8; K&R2 Sec. 5.4 p. 102; ANSI
  1282.     Sec. 4.1.5, Sec. 3.2.2.3; ISO Sec. 7.1.6, Sec. 6.2.2.3;
  1283.     Rationale Sec. 4.1.5; H&S Sec. 5.3.2 p. 122, Sec. 11.1 p. 292.
  1284.  
  1285.  
  1286. 5.5:    How should NULL be defined on a machine which uses a nonzero bit
  1287.     pattern as the internal representation of a null pointer?
  1288.  
  1289. A:    The same as on any other machine: as 0 (or ((void *)0)).
  1290.  
  1291.     Whenever a programmer requests a null pointer, either by writing
  1292.     "0" or "NULL," it is the compiler's responsibility to generate
  1293.     whatever bit pattern the machine uses for that null pointer.
  1294.     Therefore, #defining NULL as 0 on a machine for which internal
  1295.     null pointers are nonzero is as valid as on any other: the
  1296.     compiler must always be able to generate the machine's correct
  1297.     null pointers in response to unadorned 0's seen in pointer
  1298.     contexts.  See also questions 5.2, 5.10, and 5.17.
  1299.  
  1300.     References: ANSI Sec. 4.1.5; ISO Sec. 7.1.6; Rationale
  1301.     Sec. 4.1.5.
  1302.  
  1303. 5.6:    If NULL were defined as follows:
  1304.  
  1305.         #define NULL ((char *)0)
  1306.  
  1307.     wouldn't that make function calls which pass an uncast NULL
  1308.     work?
  1309.  
  1310. A:    Not in general.  The problem is that there are machines which
  1311.     use different internal representations for pointers to different
  1312.     types of data.  The suggested definition would make uncast NULL
  1313.     arguments to functions expecting pointers to characters work
  1314.     correctly, but pointer arguments of other types would still be
  1315.     problematical, and legal constructions such as
  1316.  
  1317.         FILE *fp = NULL;
  1318.  
  1319.     could fail.
  1320.  
  1321.     Nevertheless, ANSI C allows the alternate definition
  1322.  
  1323.         #define NULL ((void *)0)
  1324.  
  1325.     for NULL.  Besides potentially helping incorrect programs to
  1326.     work (but only on machines with homogeneous pointers, thus
  1327.     questionably valid assistance), this definition may catch
  1328.     programs which use NULL incorrectly (e.g. when the ASCII NUL
  1329.     character was really intended; see question 5.9).
  1330.  
  1331.     References: Rationale Sec. 4.1.5.
  1332.  
  1333. 5.9:    If NULL and 0 are equivalent as null pointer constants, which
  1334.     should I use?
  1335.  
  1336. A:    Many programmers believe that NULL should be used in all pointer
  1337.     contexts, as a reminder that the value is to be thought of as a
  1338.     pointer.  Others feel that the confusion surrounding NULL and 0
  1339.     is only compounded by hiding 0 behind a macro, and prefer to use
  1340.     unadorned 0 instead.  There is no one right answer.  (See also
  1341.     questions 9.2 and 17.10.)  C programmers must understand that
  1342.     NULL and 0 are interchangeable in pointer contexts, and that an
  1343.     uncast 0 is perfectly acceptable.  Any usage of NULL (as opposed
  1344.     to 0) should be considered a gentle reminder that a pointer is
  1345.     involved; programmers should not depend on it (either for their
  1346.     own understanding or the compiler's) for distinguishing pointer
  1347.     0's from integer 0's.
  1348.  
  1349.     NULL should *not* be used when another kind of 0 is required,
  1350.     even though it might work, because doing so sends the wrong
  1351.     stylistic message.  (Furthermore, ANSI allows the definition of
  1352.     NULL to be ((void *)0), which will not work at all in non-
  1353.     pointer contexts.)  In particular, do not use NULL when the
  1354.     ASCII null character (NUL) is desired.  Provide your own
  1355.     definition
  1356.  
  1357.         #define NUL '\0'
  1358.  
  1359.     if you must.
  1360.  
  1361.     References: K&R1 Sec. 5.4 pp. 97-8; K&R2 Sec. 5.4 p. 102.
  1362.  
  1363. 5.10:    But wouldn't it be better to use NULL (rather than 0), in case
  1364.     the value of NULL changes, perhaps on a machine with nonzero
  1365.     internal null pointers?
  1366.  
  1367. A:    No.  (Using NULL may be preferable, but not for this reason.)
  1368.     Although symbolic constants are often used in place of numbers
  1369.     because the numbers might change, this is *not* the reason that
  1370.     NULL is used in place of 0.  Once again, the language guarantees
  1371.     that source-code 0's (in pointer contexts) generate null
  1372.     pointers.  NULL is used only as a stylistic convention.  See
  1373.     questions 5.5 and 9.2.
  1374.  
  1375. 5.12:    I use the preprocessor macro
  1376.  
  1377.         #define Nullptr(type) (type *)0
  1378.  
  1379.     to help me build null pointers of the correct type.
  1380.  
  1381. A:    This trick, though popular and superficially attractive, does
  1382.     not buy much.  It is not needed in assignments and comparisons;
  1383.     see question 5.2.  It does not even save keystrokes.  Its use
  1384.     may suggest to the reader that the program's author is shaky on
  1385.     the subject of null pointers, requiring that the #definition of
  1386.     the macro, its invocations, and *all* other pointer usages be
  1387.     checked.  See also questions 9.1 and 10.2.
  1388.  
  1389. 5.13:    This is strange.  NULL is guaranteed to be 0, but the null
  1390.     pointer is not?
  1391.  
  1392. A:    When the term "null" or "NULL" is casually used, one of several
  1393.     things may be meant:
  1394.  
  1395.     1.    The conceptual null pointer, the abstract language concept
  1396.         defined in question 5.1.  It is implemented with...
  1397.  
  1398.     2.    The internal (or run-time) representation of a null
  1399.         pointer, which may or may not be all-bits-0 and which may
  1400.         be different for different pointer types.  The actual
  1401.         values should be of concern only to compiler writers.
  1402.         Authors of C programs never see them, since they use...
  1403.  
  1404.     3.    The null pointer constant, which is a constant integer 0
  1405.         (see question 5.2).  It is often hidden behind...
  1406.  
  1407.     4.    The NULL macro, which is #defined to be "0" or
  1408.         "((void *)0)" (see question 5.4).  Finally, as red
  1409.         herrings, we have...
  1410.  
  1411.     5.    The ASCII null character (NUL), which does have all bits
  1412.         zero, but has no necessary relation to the null pointer
  1413.         except in name; and...
  1414.  
  1415.     6.    The "null string," which is another name for the empty
  1416.         string ("").  Using the term "null string" can be
  1417.         confusing in C, because an empty string involves a null
  1418.         ('\0') character, but *not* a null pointer, which brings
  1419.         us full circle...
  1420.  
  1421.     This article uses the phrase "null pointer" (in lower case) for
  1422.     sense 1, the character "0" or the phrase "null pointer constant"
  1423.     for sense 3, and the capitalized word "NULL" for sense 4.
  1424.  
  1425. 5.14:    Why is there so much confusion surrounding null pointers?  Why
  1426.     do these questions come up so often?
  1427.  
  1428. A:    C programmers traditionally like to know more than they need to
  1429.     about the underlying machine implementation.  The fact that null
  1430.     pointers are represented both in source code, and internally to
  1431.     most machines, as zero invites unwarranted assumptions.  The use
  1432.     of a preprocessor macro (NULL) may seem to suggest that the
  1433.     value could change some day, or on some weird machine.  The
  1434.     construct "if(p == 0)" is easily misread as calling for
  1435.     conversion of p to an integral type, rather than 0 to a pointer
  1436.     type, before the comparison.  Finally, the distinction between
  1437.     the several uses of the term "null" (listed in question 5.13
  1438.     above) is often overlooked.
  1439.  
  1440.     One good way to wade out of the confusion is to imagine that C
  1441.     used a keyword (perhaps "nil", like Pascal) as a null pointer
  1442.     constant.  The compiler could either turn "nil" into the correct
  1443.     type of null pointer when it could determine the type from the
  1444.     source code, or complain when it could not.  Now in fact, in C
  1445.     the keyword for a null pointer constant is not "nil" but "0",
  1446.     which works almost as well, except that an uncast "0" in a non-
  1447.     pointer context generates an integer zero instead of an error
  1448.     message, and if that uncast 0 was supposed to be a null pointer
  1449.     constant, the code may not work.
  1450.  
  1451. 5.15:    I'm confused.  I just can't understand all this null pointer
  1452.     stuff.
  1453.  
  1454. A:    Follow these two simple rules:
  1455.  
  1456.     1.    When you want a null pointer constant in source code,
  1457.         use "0" or "NULL".
  1458.  
  1459.     2.    If the usage of "0" or "NULL" is an argument in a
  1460.         function call, cast it to the pointer type expected by
  1461.         the function being called.
  1462.  
  1463.     The rest of the discussion has to do with other people's
  1464.     misunderstandings, with the internal representation of null
  1465.     pointers (which you shouldn't need to know), and with ANSI C
  1466.     refinements.  Understand questions 5.1, 5.2, and 5.4, and
  1467.     consider 5.3, 5.9, 5.13, and 5.14, and you'll do fine.
  1468.  
  1469. 5.16:    Given all the confusion surrounding null pointers, wouldn't it
  1470.     be easier simply to require them to be represented internally by
  1471.     zeroes?
  1472.  
  1473. A:    If for no other reason, doing so would be ill-advised because it
  1474.     would unnecessarily constrain implementations which would
  1475.     otherwise naturally represent null pointers by special, nonzero
  1476.     bit patterns, particularly when those values would trigger
  1477.     automatic hardware traps for invalid accesses.
  1478.  
  1479.     Besides, what would such a requirement really accomplish?
  1480.     Proper understanding of null pointers does not require knowledge
  1481.     of the internal representation, whether zero or nonzero.
  1482.     Assuming that null pointers are internally zero does not make
  1483.     any code easier to write (except for a certain ill-advised usage
  1484.     of calloc(); see question 7.31).  Known-zero internal pointers
  1485.     would not obviate casts in function calls, because the *size* of
  1486.     the pointer might still be different from that of an int.  (If
  1487.     "nil" were used to request null pointers, as mentioned in
  1488.     question 5.14 above, the urge to assume an internal zero
  1489.     representation would not even arise.)
  1490.  
  1491. 5.17:    Seriously, have any actual machines really used nonzero null
  1492.     pointers, or different representations for pointers to different
  1493.     types?
  1494.  
  1495. A:    The Prime 50 series used segment 07777, offset 0 for the null
  1496.     pointer, at least for PL/I.  Later models used segment 0, offset
  1497.     0 for null pointers in C, necessitating new instructions such as
  1498.     TCNP (Test C Null Pointer), evidently as a sop to all the extant
  1499.     poorly-written C code which made incorrect assumptions.  Older,
  1500.     word-addressed Prime machines were also notorious for requiring
  1501.     larger byte pointers (char *'s) than word pointers (int *'s).
  1502.  
  1503.     The Eclipse MV series from Data General has three
  1504.     architecturally supported pointer formats (word, byte, and bit
  1505.     pointers), two of which are used by C compilers: byte pointers
  1506.     for char * and void *, and word pointers for everything else.
  1507.  
  1508.     Some Honeywell-Bull mainframes use the bit pattern 06000 for
  1509.     (internal) null pointers.
  1510.  
  1511.     The CDC Cyber 180 Series has 48-bit pointers consisting of a
  1512.     ring, segment, and offset.  Most users (in ring 11) have null
  1513.     pointers of 0xB00000000000.  It was common on old CDC ones-
  1514.     complement machines to use an all-one-bits word as a special
  1515.     flag for all kinds of data, including invalid addresses.
  1516.  
  1517.     The old HP 3000 series uses a different addressing scheme for
  1518.     byte addresses than for word addresses; like several of the
  1519.     machines above it therefore uses different representations for
  1520.     char * and void * pointers than for other pointers.
  1521.  
  1522.     The Symbolics Lisp Machine, a tagged architecture, does not even
  1523.     have conventional numeric pointers; it uses the pair <NIL, 0>
  1524.     (basically a nonexistent <object, offset> handle) as a C null
  1525.     pointer.
  1526.  
  1527.     Depending on the "memory model" in use, 8086-family processors
  1528.     (PC compatibles) may use 16-bit data pointers and 32-bit
  1529.     function pointers, or vice versa.
  1530.  
  1531.     Some 64-bit Cray machines represent int * in the lower 48 bits
  1532.     of a word; char * additionally uses the upper 16 bits to
  1533.     indicate a byte address within a word.
  1534.  
  1535.     References: K&R1 Sec. A14.4 p. 211.
  1536.  
  1537. 5.20:    What does a run-time "null pointer assignment" error mean?  How
  1538.     do I track it down?
  1539.  
  1540. A:    This message, which typically occurs with MS-DOS compilers (see,
  1541.     therefore, section 19) means that you've written, via a null
  1542.     (perhaps because uninitialized) pointer, to location 0.  (See
  1543.     also question 16.8.)
  1544.  
  1545.     A debugger may let you set a data breakpoint or watchpoint or
  1546.     something on location 0.  Alternatively, you could write a bit
  1547.     of code to stash away a copy of 20 or so bytes from location 0,
  1548.     and periodically check that the memory at location 0 hasn't
  1549.     changed.
  1550.  
  1551.  
  1552. Section 6.  Arrays and Pointers
  1553.  
  1554. 6.1:    I had the definition char a[6] in one source file, and in
  1555.     another I declared extern char *a.  Why didn't it work?
  1556.  
  1557. A:    The declaration extern char *a simply does not match the actual
  1558.     definition.  The type pointer-to-type-T is not the same as array-
  1559.     of-type-T.  Use extern char a[].
  1560.  
  1561.     References: ANSI Sec. 3.5.4.2; ISO Sec. 6.5.4.2; CT&P Sec. 3.3
  1562.     pp. 33-4, Sec. 4.5 pp. 64-5.
  1563.  
  1564. 6.2:    But I heard that char a[] was identical to char *a.
  1565.  
  1566. A:    Not at all.  (What you heard has to do with formal parameters to
  1567.     functions; see question 6.4.)  Arrays are not pointers.  The
  1568.     array declaration char a[6] requests that space for six
  1569.     characters be set aside, to be known by the name "a."  That is,
  1570.     there is a location named "a" at which six characters can sit.
  1571.     The pointer declaration char *p, on the other hand, requests a
  1572.     place which holds a pointer, to be known by the name "p."  This
  1573.     pointer can point almost anywhere: to any char, or to any
  1574.     contiguous array of chars, or nowhere (see also questions 5.1
  1575.     and 1.30).
  1576.  
  1577.     As usual, a picture is worth a thousand words.  The declarations
  1578.  
  1579.         char a[] = "hello";
  1580.         char *p = "world";
  1581.  
  1582.     would initialize data structures which could be represented like
  1583.     this:
  1584.            +---+---+---+---+---+---+
  1585.         a: | h | e | l | l | o |\0 |
  1586.            +---+---+---+---+---+---+
  1587.            +-----+     +---+---+---+---+---+---+
  1588.         p: |  *======> | w | o | r | l | d |\0 |
  1589.            +-----+     +---+---+---+---+---+---+
  1590.  
  1591.     It is important to realize that a reference like *x*[3]
  1592.     generates different code depending on whether *x* is an array or
  1593.     a pointer.  Given the declarations above, when the compiler sees
  1594.     the expression a[3], it emits code to start at the location "a,"
  1595.     move three past it, and fetch the character there.  When it sees
  1596.     the expression p[3], it emits code to start at the location "p,"
  1597.     fetch the pointer value there, add three to the pointer, and
  1598.     finally fetch the character pointed to.  In other words, a[3] is
  1599.     three places past (the start of) the object *named* a, while
  1600.     p[3] is three places past the object *pointed to* by p.  In the
  1601.     example above, both a[3] and p[3] happen to be the character
  1602.     'l', but the compiler gets there differently.
  1603.  
  1604.     References: K&R2 Sec. 5.5 p. 104; CT&P Sec. 4.5 pp. 64-5.
  1605.  
  1606. 6.3:    So what is meant by the "equivalence of pointers and arrays" in
  1607.     C?
  1608.  
  1609. A:    Much of the confusion surrounding arrays and pointers in C can
  1610.     be traced to a misunderstanding of this statement.  Saying that
  1611.     arrays and pointers are "equivalent" means neither that they are
  1612.     identical nor even interchangeable.
  1613.  
  1614.     "Equivalence" refers to the following key definition:
  1615.  
  1616.         An lvalue of type array-of-T which appears in an
  1617.         expression decays (with three exceptions) into a
  1618.         pointer to its first element; the type of the
  1619.         resultant pointer is pointer-to-T.
  1620.  
  1621.     (The exceptions are when the array is the operand of a sizeof or
  1622.     & operator, or is a string literal initializer for a character
  1623.     array.)
  1624.  
  1625.     As a consequence of this definition, the compiler doesn't apply
  1626.     the array subscripting operator [] that differently to arrays
  1627.     and pointers, after all.  In an expression of the form a[i], the
  1628.     array decays into a pointer, following the rule above, and is
  1629.     then subscripted just as would be a pointer variable in the
  1630.     expression p[i] (although the eventual memory accesses will be
  1631.     different, as explained in question 6.2).  If you were to assign
  1632.     the array's address to the pointer:
  1633.  
  1634.         p = a;
  1635.  
  1636.     then p[3] and a[3] would access the same element.
  1637.  
  1638.     See also question 6.8.
  1639.  
  1640.     References: K&R1 Sec. 5.3 pp. 93-6; K&R2 Sec. 5.3 p. 99; ANSI
  1641.     Sec. 3.2.2.1, Sec. 3.3.2.1, Sec. 3.3.6; ISO Sec. 6.2.2.1,
  1642.     Sec. 6.3.2.1, Sec. 6.3.6; H&S Sec. 5.4.1 p. 124.
  1643.  
  1644. 6.4:    Then why are array and pointer declarations interchangeable as
  1645.     function formal parameters?
  1646.  
  1647. A:    It's supposed to be a convenience.
  1648.  
  1649.     Since arrays decay immediately into pointers, an array is never
  1650.     actually passed to a function.  Allowing pointer parameters to
  1651.     be declared as arrays is a simply a way of making it look as
  1652.     though the array was being passed -- a programmer may wish to
  1653.     emphasize that a parameter is traditionally treated as if it
  1654.     were an array, or that an array (strictly speaking, the address)
  1655.     is traditionally passed.  As a convenience, therefore, any
  1656.     parameter declarations which "look like" arrays, e.g.
  1657.  
  1658.         f(a)
  1659.         char a[];
  1660.         { ... }
  1661.  
  1662.     are treated by the compiler as if they were pointers, since that
  1663.     is what the function will receive if an array is passed:
  1664.  
  1665.         f(a)
  1666.         char *a;
  1667.         { ... }
  1668.  
  1669.     This conversion holds only within function formal parameter
  1670.     declarations, nowhere else.  If the conversion bothers you,
  1671.     avoid it; many people have concluded that the confusion it
  1672.     causes outweighs the small advantage of having the declaration
  1673.     "look like" the call or the uses within the function.
  1674.  
  1675.     See also question 6.21.
  1676.  
  1677.     References: K&R1 Sec. 5.3 p. 95, Sec. A10.1 p. 205; K&R2
  1678.     Sec. 5.3 p. 100, Sec. A8.6.3 p. 218, Sec. A10.1 p. 226; ANSI
  1679.     Sec. 3.5.4.3, Sec. 3.7.1, Sec. 3.9.6; ISO Sec. 6.5.4.3,
  1680.     Sec. 6.7.1, Sec. 6.9.6; H&S Sec. 9.3 p. 271; CT&P Sec. 3.3 pp.
  1681.     33-4.
  1682.  
  1683. 6.7:    How can an array be an lvalue, if you can't assign to it?
  1684.  
  1685. A:    The ANSI C Standard defines a "modifiable lvalue," which an
  1686.     array is not.
  1687.  
  1688.     References: ANSI Sec. 3.2.2.1; ISO Sec. 6.2.2.1; Rationale
  1689.     Sec. 3.2.2.1; H&S Sec. 7.1 p. 179.
  1690.  
  1691. 6.8:    Practically speaking, what is the difference between arrays and
  1692.     pointers?
  1693.  
  1694. A:    Arrays automatically allocate space, but can't be relocated or
  1695.     resized.  Pointers must be explicitly assigned to point to
  1696.     allocated space (perhaps using malloc), but can be reassigned
  1697.     (i.e. pointed at different objects) at will, and have many other
  1698.     uses besides serving as the base of blocks of memory.
  1699.  
  1700.     Due to the so-called equivalence of arrays and pointers (see
  1701.     question 6.3), arrays and pointers often seem interchangeable,
  1702.     and in particular a pointer to a block of memory assigned by
  1703.     malloc is frequently treated (and can be referenced using [])
  1704.     exactly as if it were a true array.  See questions 6.14 and
  1705.     6.16.  (Be careful with sizeof, though.)
  1706.  
  1707.     See also questions 1.32 and 20.14.
  1708.  
  1709. 6.9:    Someone explained to me that arrays were really just constant
  1710.     pointers.
  1711.  
  1712. A:    This is a bit of an oversimplification.  An array name is
  1713.     "constant" in that it cannot be assigned to, but an array is
  1714.     *not* a pointer, as the discussion and pictures in question 6.2
  1715.     should make clear.  See also questions 6.3 and 6.8.
  1716.  
  1717. 6.11:    I came across some "joke" code containing the "expression"
  1718.     5["abcdef"] .  How can this be legal C?
  1719.  
  1720. A:    Yes, Virginia, array subscripting is commutative in C.  This
  1721.     curious fact follows from the pointer definition of array
  1722.     subscripting, namely that a[e] is identical to *((a)+(e)), for
  1723.     *any* two expressions a and e, as long as one of them is a
  1724.     pointer expression and one is integral.  This unsuspected
  1725.     commutativity is often mentioned in C texts as if it were
  1726.     something to be proud of, but it finds no useful application
  1727.     outside of the Obfuscated C Contest (see question 20.36).
  1728.  
  1729.     References: Rationale Sec. 3.3.2.1; H&S Sec. 5.4.1 p. 124,
  1730.     Sec. 7.4.1 pp. 186-7.
  1731.  
  1732. 6.12:    Since array references decay into pointers, if arr is an array,
  1733.     what's the difference between arr and &arr?
  1734.  
  1735. A:    The type.
  1736.  
  1737.     In Standard C, &arr yields a pointer, of type pointer-to-array-
  1738.     of-T, to the entire array.  (In pre-ANSI C, the & in &arr
  1739.     generally elicited a warning, and was generally ignored.)  Under
  1740.     all C compilers, a simple reference (without an explicit &) to
  1741.     an array yields a pointer, of type pointer-to-T, to the array's
  1742.     first element.  (See also questions 6.3, 6.13, and 6.18.)
  1743.  
  1744.     References: ANSI Sec. 3.2.2.1, Sec. 3.3.3.2; ISO Sec. 6.2.2.1,
  1745.     Sec. 6.3.3.2; Rationale Sec. 3.3.3.2; H&S Sec. 7.5.6 p. 198.
  1746.  
  1747. 6.13:    How do I declare a pointer to an array?
  1748.  
  1749. A:    Usually, you don't want to.  When people speak casually of a
  1750.     pointer to an array, they usually mean a pointer to its first
  1751.     element.
  1752.  
  1753.     Instead of a pointer to an array, consider using a pointer to
  1754.     one of the array's elements.  Arrays of type T decay into
  1755.     pointers to type T (see question 6.3), which is convenient;
  1756.     subscripting or incrementing the resultant pointer will access
  1757.     the individual members of the array.  True pointers to arrays,
  1758.     when subscripted or incremented, step over entire arrays, and
  1759.     are generally useful only when operating on arrays of arrays, if
  1760.     at all.  (See question 6.18.)
  1761.  
  1762.     If you really need to declare a pointer to an entire array, use
  1763.     something like "int (*ap)[N];" where N is the size of the array.
  1764.     (See also question 1.21.)  If the size of the array is unknown,
  1765.     N can in principle be omitted, but the resulting type, "pointer
  1766.     to array of unknown size," is useless.
  1767.  
  1768.     See also question 6.12 above.
  1769.  
  1770.     References: ANSI Sec. 3.2.2.1; ISO Sec. 6.2.2.1.
  1771.  
  1772. 6.14:    How can I set an array's size at compile time?
  1773.     How can I avoid fixed-sized arrays?
  1774.  
  1775. A:    The equivalence between arrays and pointers (see question 6.3)
  1776.     allows a pointer to malloc'ed memory to simulate an array
  1777.     quite effectively.  After executing
  1778.  
  1779.         #include <stdlib.h>
  1780.         int *dynarray = (int *)malloc(10 * sizeof(int));
  1781.  
  1782.     (and if the call to malloc() succeeds), you can reference
  1783.     dynarray[i] (for i from 0 to 9) just as if dynarray were a
  1784.     conventional, statically-allocated array (int a[10]).  See also
  1785.     question 6.16.
  1786.  
  1787. 6.15:    How can I declare local arrays of a size matching a passed-in
  1788.     array?
  1789.  
  1790. A:    You can't, in C.  Array dimensions must be compile-time
  1791.     constants.  (gcc provides parameterized arrays as an extension.)
  1792.     You'll have to use malloc(), and remember to call free() before
  1793.     the function returns.  See also questions 6.14, 6.16, 6.19,
  1794.     7.22, and maybe 7.32.
  1795.  
  1796.     References: ANSI Sec. 3.4, Sec. 3.5.4.2; ISO Sec. 6.4,
  1797.     Sec. 6.5.4.2.
  1798.  
  1799. 6.16:    How can I dynamically allocate a multidimensional array?
  1800.  
  1801. A:    It is usually best to allocate an array of pointers, and then
  1802.     initialize each pointer to a dynamically-allocated "row."  Here
  1803.     is a two-dimensional example:
  1804.  
  1805.         #include <stdlib.h>
  1806.  
  1807.         int **array1 = (int **)malloc(nrows * sizeof(int *));
  1808.         for(i = 0; i < nrows; i++)
  1809.             array1[i] = (int *)malloc(ncolumns * sizeof(int));
  1810.  
  1811.     (In real code, of course, all of malloc's return values would
  1812.     be checked.)
  1813.  
  1814.     You can keep the array's contents contiguous, while making later
  1815.     reallocation of individual rows difficult, with a bit of
  1816.     explicit pointer arithmetic:
  1817.  
  1818.         int **array2 = (int **)malloc(nrows * sizeof(int *));
  1819.         array2[0] = (int *)malloc(nrows * ncolumns * sizeof(int));
  1820.         for(i = 1; i < nrows; i++)
  1821.             array2[i] = array2[0] + i * ncolumns;
  1822.  
  1823.     In either case, the elements of the dynamic array can be
  1824.     accessed with normal-looking array subscripts: arrayx[i][j] (for
  1825.     0 <= i <= NROWS and 0 <= j <= NCOLUMNS).
  1826.  
  1827.     If the double indirection implied by the above schemes is for
  1828.     some reason unacceptable, you can simulate a two-dimensional
  1829.     array with a single, dynamically-allocated one-dimensional
  1830.     array:
  1831.  
  1832.         int *array3 = (int *)malloc(nrows * ncolumns * sizeof(int));
  1833.  
  1834.     However, you must now perform subscript calculations manually,
  1835.     accessing the i,jth element with array3[i * ncolumns + j].  (A
  1836.     macro could hide the explicit calculation, but invoking it would
  1837.     require parentheses and commas which wouldn't look exactly like
  1838.     multidimensional array syntax, and the macro would need access
  1839.     to at least one of the dimensions, as well.  See also question
  1840.     6.19.)
  1841.  
  1842.     Finally, you could use pointers to arrays:
  1843.  
  1844.         int (*array4)[NCOLUMNS] =
  1845.             (int (*)[NCOLUMNS])malloc(nrows * sizeof(*array4));
  1846.  
  1847.     but the syntax starts getting horrific and at most one dimension
  1848.     may be specified at run time.
  1849.  
  1850.     With all of these techniques, you may of course need to remember
  1851.     to free the arrays (which may take several steps; see question
  1852.     7.23) when they are no longer needed, and you cannot necessarily
  1853.     intermix dynamically-allocated arrays with conventional,
  1854.     statically-allocated ones (see question 6.20, and also question
  1855.     6.18).
  1856.  
  1857.     All of these techniques can also be extended to three or more
  1858.     dimensions.
  1859.  
  1860. 6.17:    Here's a neat trick: if I write
  1861.  
  1862.         int realarray[10];
  1863.         int *array = &realarray[-1];
  1864.  
  1865.     I can treat "array" as if it were a 1-based array.
  1866.  
  1867. A:    Although this technique is attractive (and was used in old
  1868.     editions of the book _Numerical Recipes in C_), it does not
  1869.     conform to the C standards.  Pointer arithmetic is defined only
  1870.     as long as the pointer points within the same allocated block of
  1871.     memory, or to the imaginary "terminating" element one past it;
  1872.     otherwise, the behavior is undefined, *even if the pointer is
  1873.     not dereferenced*.  The code above could fail if, while
  1874.     subtracting the offset, an illegal address were generated
  1875.     (perhaps because the address tried to "wrap around" past the
  1876.     beginning of some memory segment).
  1877.  
  1878.     References: K&R2 Sec. 5.3 p. 100, Sec. 5.4 pp. 102-3, Sec. A7.7
  1879.     pp. 205-6; ANSI Sec. 3.3.6; ISO Sec. 6.3.6; Rationale
  1880.     Sec. 3.2.2.3.
  1881.  
  1882. 6.18:    My compiler complained when I passed a two-dimensional array to
  1883.     a function expecting a pointer to a pointer.
  1884.  
  1885. A:    The rule (see question 6.3) by which arrays decay into pointers
  1886.     is not applied recursively.  An array of arrays (i.e. a two-
  1887.     dimensional array in C) decays into a pointer to an array, not a
  1888.     pointer to a pointer.  Pointers to arrays can be confusing, and
  1889.     must be treated carefully; see also question 6.13.  (The
  1890.     confusion is heightened by the existence of incorrect compilers,
  1891.     including some old versions of pcc and pcc-derived lints, which
  1892.     improperly accept assignments of multi-dimensional arrays to
  1893.     multi-level pointers.)
  1894.  
  1895.     If you are passing a two-dimensional array to a function:
  1896.  
  1897.         int array[NROWS][NCOLUMNS];
  1898.         f(array);
  1899.  
  1900.     the function's declaration must match:
  1901.  
  1902.         f(int a[][NCOLUMNS])
  1903.         { ... }
  1904.  
  1905.     or
  1906.  
  1907.         f(int (*ap)[NCOLUMNS])  /* ap is a pointer to an array */
  1908.         { ... }
  1909.  
  1910.     In the first declaration, the compiler performs the usual
  1911.     implicit parameter rewriting of "array of array" to "pointer to
  1912.     array" (see questions 6.3 and 6.4); in the second form the
  1913.     pointer declaration is explicit.  Since the called function does
  1914.     not allocate space for the array, it does not need to know the
  1915.     overall size, so the number of rows, NROWS, can be omitted.  The
  1916.     "shape" of the array is still important, so the column dimension
  1917.     NCOLUMNS (and, for three- or more dimensional arrays, the
  1918.     intervening ones) must be retained.
  1919.  
  1920.     If a function is already declared as accepting a pointer to a
  1921.     pointer, it is probably meaningless to pass a two-dimensional
  1922.     array directly to it.
  1923.  
  1924.     See also questions 6.12 and 6.15.
  1925.  
  1926.     References: K&R1 Sec. 5.10 p. 110; K&R2 Sec. 5.9 p. 113; H&S
  1927.     Sec. 5.4.3 p. 126.
  1928.  
  1929. 6.19:    How do I write functions which accept two-dimensional arrays
  1930.     when the "width" is not known at compile time?
  1931.  
  1932. A:    It's not easy.  One way is to pass in a pointer to the [0][0]
  1933.     element, along with the two dimensions, and simulate array
  1934.     subscripting "by hand:"
  1935.  
  1936.         f2(aryp, nrows, ncolumns)
  1937.         int *aryp;
  1938.         int nrows, ncolumns;
  1939.         { ... array[i][j] is accessed as aryp[i * ncolumns + j] ... }
  1940.  
  1941.     This function could be called with the array from question 6.18
  1942.     as
  1943.  
  1944.         f2(&array[0][0], NROWS, NCOLUMNS);
  1945.  
  1946.     It must be noted, however, that a program which performs
  1947.     multidimensional array subscripting "by hand" in this way is not
  1948.     in strict conformance with the ANSI C Standard; according to an
  1949.     official interpretation, the behavior of accessing
  1950.     (&array[0][0])[x] is not defined for x >= NCOLUMNS.
  1951.  
  1952.     gcc allows local arrays to be declared having sizes which are
  1953.     specified by a function's arguments, but this is a nonstandard
  1954.     extension.
  1955.  
  1956.     When you want to be able to use a function on multidimensional
  1957.     arrays of various sizes, one solution is to simulate all the
  1958.     arrays dynamically, as in question 6.16.
  1959.  
  1960.     See also questions 6.18, 6.20, and 6.15.
  1961.  
  1962.     References: ANSI Sec. 3.3.6; ISO Sec. 6.3.6.
  1963.  
  1964. 6.20:    How can I use statically- and dynamically-allocated
  1965.     multidimensional arrays interchangeably when passing them to
  1966.     functions?
  1967.  
  1968. A:    There is no single perfect method.  Given the declarations
  1969.  
  1970.         int array[NROWS][NCOLUMNS];
  1971.         int **array1;            /* ragged */
  1972.         int **array2;            /* contiguous */
  1973.         int *array3;            /* "flattened" */
  1974.         int (*array4)[NCOLUMNS];
  1975.  
  1976.     with the pointers initialized as in the code fragments in
  1977.     question 6.16, and functions declared as
  1978.  
  1979.         f1(int a[][NCOLUMNS], int nrows, int ncolumns);
  1980.         f2(int *aryp, int nrows, int ncolumns);
  1981.         f3(int **pp, int nrows, int ncolumns);
  1982.  
  1983.     where f1() accepts a conventional two-dimensional array, f2()
  1984.     accepts a "flattened" two-dimensional array, and f3() accepts a
  1985.     pointer-to-pointer, simulated array (see also questions 6.18 and
  1986.     6.19), the following calls should work as expected:
  1987.  
  1988.         f1(array, NROWS, NCOLUMNS);
  1989.         f1(array4, nrows, NCOLUMNS);
  1990.         f2(&array[0][0], NROWS, NCOLUMNS);
  1991.         f2(*array, NROWS, NCOLUMNS);
  1992.         f2(*array2, nrows, ncolumns);
  1993.         f2(array3, nrows, ncolumns);
  1994.         f2(*array4, nrows, NCOLUMNS);
  1995.         f3(array1, nrows, ncolumns);
  1996.         f3(array2, nrows, ncolumns);
  1997.  
  1998.     The following two calls would probably work on most systems, but
  1999.     involve questionable casts, and work only if the dynamic
  2000.     ncolumns matches the static NCOLUMNS:
  2001.  
  2002.         f1((int (*)[NCOLUMNS])(*array2), nrows, ncolumns);
  2003.         f1((int (*)[NCOLUMNS])array3, nrows, ncolumns);
  2004.  
  2005.     It must again be noted that passing &array[0][0] (or,
  2006.     equivalently, *array) to f2() is not strictly conforming; see
  2007.     question 6.19.
  2008.  
  2009.     If you can understand why all of the above calls work and are
  2010.     written as they are, and if you understand why the combinations
  2011.     that are not listed would not work, then you have a *very* good
  2012.     understanding of arrays and pointers in C.
  2013.  
  2014.     Rather than worrying about all of this, one approach to using
  2015.     multidimensional arrays of various sizes is to make them *all*
  2016.     dynamic, as in question 6.16.  If there are no static
  2017.     multidimensional arrays -- if all arrays are allocated like
  2018.     array1 or array2 in question 6.16 -- then all functions can be
  2019.     written like f3().
  2020.  
  2021. 6.21:    Why doesn't sizeof properly report the size of an array when the
  2022.     array is a parameter to a function?
  2023.  
  2024. A:    The compiler pretends that the array parameter was declared as a
  2025.     pointer (see question 6.4), and sizeof reports the size of the
  2026.     pointer.
  2027.  
  2028.     References: H&S Sec. 7.5.2 p. 195.
  2029.  
  2030.  
  2031. Section 7. Memory Allocation
  2032.  
  2033. 7.1:    Why doesn't this fragment work?
  2034.  
  2035.         char *answer;
  2036.         printf("Type something:\n");
  2037.         gets(answer);
  2038.         printf("You typed \"%s\"\n", answer);
  2039.  
  2040. A:    The pointer variable answer(), which is handed to gets() as the
  2041.     location into which the response should be stored, has not been
  2042.     set to point to any valid storage.  That is, we cannot say where
  2043.     the pointer answer() points.  (Since local variables are not
  2044.     initialized, and typically contain garbage, it is not even
  2045.     guaranteed that answer() starts out as a null pointer.  See
  2046.     questions 1.30 and 5.1.)
  2047.  
  2048.     The simplest way to correct the question-asking program is to
  2049.     use a local array, instead of a pointer, and let the compiler
  2050.     worry about allocation:
  2051.  
  2052.         #include <stdio.h>
  2053.         #include <string.h>
  2054.  
  2055.         char answer[100], *p;
  2056.         printf("Type something:\n");
  2057.         fgets(answer, sizeof answer, stdin);
  2058.         if((p = strchr(answer, '\n')) != NULL)
  2059.             *p = '\0';
  2060.         printf("You typed \"%s\"\n", answer);
  2061.  
  2062.     This example also uses fgets() instead of gets(), so that the
  2063.     end of the array cannot be overwritten.  (See question 12.23.
  2064.     Unfortunately for this example, fgets() does not automatically
  2065.     delete the trailing \n, as gets() would.)  It would also be
  2066.     possible to use malloc() to allocate the answer buffer.
  2067.  
  2068. 7.2:    I can't get strcat() to work.  I tried
  2069.  
  2070.         char *s1 = "Hello, ";
  2071.         char *s2 = "world!";
  2072.         char *s3 = strcat(s1, s2);
  2073.  
  2074.     but I got strange results.
  2075.  
  2076. A:    As in question 7.1 above, the main problem here is that space
  2077.     for the concatenated result is not properly allocated.  C does
  2078.     not provide an automatically-managed string type.  C compilers
  2079.     only allocate memory for objects explicitly mentioned in the
  2080.     source code (in the case of "strings," this includes character
  2081.     arrays and string literals).  The programmer must arrange for
  2082.     sufficient space for the results of run-time operations such as
  2083.     string concatenation, typically by declaring arrays, or by
  2084.     calling malloc().
  2085.  
  2086.     strcat() performs no allocation; the second string is appended
  2087.     to the first one, in place.  Therefore, one fix would be to
  2088.     declare the first string as an array:
  2089.  
  2090.         char s1[20] = "Hello, ";
  2091.  
  2092.     Since strcat() returns the value of its first argument (s1, in
  2093.     this case), the variable s3 is superfluous.
  2094.  
  2095.     The original call to strcat() in the question actually has two
  2096.     problems: the string literal pointed to by s1, besides not being
  2097.     big enough for any concatenated text, is not necessarily
  2098.     writable at all.  See question 1.32.
  2099.  
  2100.     References: CT&P Sec. 3.2 p. 32.
  2101.  
  2102. 7.3:    But the man page for strcat() says that it takes two char *'s as
  2103.     arguments.  How am I supposed to know to allocate things?
  2104.  
  2105. A:    In general, when using pointers you *always* have to consider
  2106.     memory allocation, if only to make sure that the compiler is
  2107.     doing it for you.  If a library function's documentation does
  2108.     not explicitly mention allocation, it is usually the caller's
  2109.     problem.
  2110.  
  2111.     The Synopsis section at the top of a Unix-style man page or in
  2112.     the ANSI C standard can be misleading.  The code fragments
  2113.     presented there are closer to the function definitions used by
  2114.     an implementor than the invocations used by the caller.  In
  2115.     particular, many functions which accept pointers (e.g. to
  2116.     structures or strings) are usually called with the address of
  2117.     some object (a structure, or an array -- see questions 6.3 and
  2118.     6.4).  Other common examples are time() (see question 13.12)
  2119.     and stat().
  2120.  
  2121. 7.5:    I have a function that is supposed to return a string, but when
  2122.     it returns to its caller, the returned string is garbage.
  2123.  
  2124. A:    Make sure that the pointed-to memory is properly allocated.  The
  2125.     returned pointer should be to a statically-allocated buffer, or
  2126.     to a buffer passed in by the caller, or to memory obtained with
  2127.     malloc(), but *not* to a local (automatic) array.  In other
  2128.     words, never do something like
  2129.  
  2130.         char *itoa(int n)
  2131.         {
  2132.             char retbuf[20];        /* WRONG */
  2133.             sprintf(retbuf, "%d", n);
  2134.             return retbuf;            /* WRONG */
  2135.         }
  2136.  
  2137.     One fix (which is imperfect, especially if the function in
  2138.     question is called recursively, or if several of its return
  2139.     values are needed simultaneously) would be to declare the return
  2140.     buffer as
  2141.  
  2142.             static char retbuf[20];
  2143.  
  2144.     See also questions 12.21 and 20.1.
  2145.  
  2146.     References: ANSI Sec. 3.1.2.4; ISO Sec. 6.1.2.4.
  2147.  
  2148. 7.6:    Why am I getting "warning: assignment of pointer from integer
  2149.     lacks a cast" for calls to malloc()?
  2150.  
  2151. A:    Have you #included <stdlib.h>, or otherwise arranged for
  2152.     malloc() to be declared properly?
  2153.  
  2154.     References: H&S Sec. 4.7 p. 101.
  2155.  
  2156. 7.7:    Why does some code carefully cast the values returned by malloc
  2157.     to the pointer type being allocated?
  2158.  
  2159. A:    Before ANSI/ISO Standard C introduced the void * generic pointer
  2160.     type, these casts were typically required to silence warnings
  2161.     (and perhaps induce conversions) when assigning between
  2162.     incompatible pointer types.  (Under ANSI/ISO Standard C, these
  2163.     casts are no longer necessary.)
  2164.  
  2165.     References: H&S Sec. 16.1 pp. 386-7.
  2166.  
  2167. 7.8:    I see code like
  2168.  
  2169.         char *p = malloc(strlen(s) + 1);
  2170.         strcpy(p, s);
  2171.  
  2172.     Shouldn't that be malloc((strlen(s) + 1) * sizeof(char))?
  2173.  
  2174. A:    It's never necessary to multiply by sizeof(char), since
  2175.     sizeof(char) is, by definition, exactly 1.  (On the other hand,
  2176.     multiplying by sizeof(char) doesn't hurt, and may help by
  2177.     introducing a size_t into the expression.)  See also question
  2178.     8.9.
  2179.  
  2180.     References: ANSI Sec. 3.3.3.4; ISO Sec. 6.3.3.4; H&S Sec. 7.5.2
  2181.     p. 195.
  2182.  
  2183. 7.14:    I've heard that some operating systems don't actually allocate
  2184.     malloc'ed memory until the program tries to use it.  Is this
  2185.     legal?
  2186.  
  2187. A:    It's hard to say.  The Standard doesn't say that systems can act
  2188.     this way, but it doesn't explicitly say that they can't, either.
  2189.  
  2190.     References: ANSI Sec. 4.10.3; ISO Sec. 7.10.3.
  2191.  
  2192. 7.16:    I'm allocating a large array for some numeric work, using the
  2193.     line
  2194.  
  2195.         double *array = malloc(256 * 256 * sizeof(double));
  2196.  
  2197.     malloc() isn't returning null, but the program is acting
  2198.     strangely, as if it's overwriting memory, or malloc() isn't
  2199.     allocating as much as I asked for, or something.
  2200.  
  2201. A:    Notice that 256 x 256 is 65,536, which will not fit in a 16-bit
  2202.     int, even before you multiply it by sizeof(double).  If you need
  2203.     to allocate this much memory, you'll have to be careful.  If
  2204.     size_t (the type accepted by malloc()) is a 32-bit type on your
  2205.     machine, but int is 16 bits, you might be able to get away with
  2206.     writing 256 * (256 * sizeof(double)) (see question 3.14).
  2207.     Otherwise, you'll have to break your data structure up into
  2208.     smaller chunks, or use a 32-bit machine, or use some nonstandard
  2209.     memory allocation routines.  See also question 19.23.
  2210.  
  2211. 7.17:    I've got 8 meg of memory in my PC.  Why can I only seem to
  2212.     malloc() 640K or so?
  2213.  
  2214. A:    Under the segmented architecture of PC compatibles, it can be
  2215.     difficult to use more than 640K with any degree of transparency.
  2216.     See also question 19.23.
  2217.  
  2218. 7.19:    My program is crashing, apparently somewhere down inside malloc,
  2219.     but I can't see anything wrong with it.
  2220.  
  2221. A:    It is unfortunately very easy to corrupt malloc's internal data
  2222.     structures, and the resulting problems can be stubborn.  The
  2223.     most common source of problems is writing more to a malloc'ed
  2224.     region than it was allocated to hold; a particularly common bug
  2225.     is to malloc(strlen(s)) instead of strlen(s) + 1.  Other
  2226.     problems may involve using pointers to freed storage, freeing
  2227.     pointers twice, freeing pointers not obtained from malloc, or
  2228.     trying to realloc a null pointer (see question 7.30).
  2229.  
  2230.     See also questions 7.26, 16.8, and 18.2.
  2231.  
  2232. 7.20:    You can't use dynamically-allocated memory after you free it,
  2233.     can you?
  2234.  
  2235. A:    No.  Some early documentation for malloc() stated that the
  2236.     contents of freed memory were "left undisturbed," but this ill-
  2237.     advised guarantee was never universal and is not required by the
  2238.     C Standard.
  2239.  
  2240.     Few programmers would use the contents of freed memory
  2241.     deliberately, but it is easy to do so accidentally.  Consider
  2242.     the following (correct) code for freeing a singly-linked list:
  2243.  
  2244.         struct list *listp, *nextp;
  2245.         for(listp = base; listp != NULL; listp = nextp) {
  2246.             nextp = listp->next;
  2247.             free((void *)listp);
  2248.         }
  2249.  
  2250.     and notice what would happen if the more-obvious loop iteration
  2251.     expression listp = listp->next were used, without the temporary
  2252.     nextp pointer.
  2253.  
  2254.     References: K&R2 Sec. 7.8.5 p. 167; ANSI Sec. 4.10.3; ISO
  2255.     Sec. 7.10.3; Rationale Sec. 4.10.3.2; H&S Sec. 16.2 p. 387; CT&P
  2256.     Sec. 7.10 p. 95.
  2257.  
  2258. 7.21:    Why isn't a pointer null after calling free()?
  2259.     How unsafe is it to use (assign, compare) a pointer value after
  2260.     it's been freed?
  2261.  
  2262. A:    When you call free(), the memory pointed to by the passed
  2263.     pointer is freed, but the value of the pointer in the caller
  2264.     remains unchanged, because C's pass-by-value semantics mean that
  2265.     called functions never permanently change the values of their
  2266.     arguments.  (See also question 4.8.)
  2267.  
  2268.     A pointer value which has been freed is, strictly speaking,
  2269.     invalid, and *any* use of it, even if is not dereferenced can
  2270.     theoretically lead to trouble, though as a quality of
  2271.     implementation issue, most implementations will probably not go
  2272.     out of their way to generate exceptions for innocuous uses of
  2273.     invalid pointers.
  2274.  
  2275.     References: ANSI Sec. 4.10.3; ISO Sec. 7.10.3; Rationale
  2276.     Sec. 3.2.2.3.
  2277.  
  2278. 7.22:    When I call malloc() to allocate memory for a local pointer, do
  2279.     I have to explicitly free() it?
  2280.  
  2281. A:    Yes.  Remember that a pointer is different from what it points
  2282.     to.  Local variables are deallocated when the function returns,
  2283.     but in the case of a pointer variable, this means that the
  2284.     pointer is deallocated, *not* what it points to.  Memory
  2285.     allocated with malloc() always persists until you explicitly
  2286.     free it.  In general, for every call to malloc(), there should
  2287.     be a corresponding call to free().
  2288.  
  2289. 7.23:    I'm allocating structures which contain pointers to other
  2290.     dynamically-allocated objects.  When I free a structure, do I
  2291.     have to free each subsidiary pointer first?
  2292.  
  2293. A:    Yes.  In general, you must arrange that each pointer returned
  2294.     from malloc() be individually passed to free(), exactly once (if
  2295.     it is freed at all).
  2296.  
  2297.     A good rule of thumb is that for each call to malloc() in a
  2298.     program, you should be able to point at the call to free() which
  2299.     frees the memory allocated by that malloc() call.
  2300.  
  2301.     See also question 7.24.
  2302.  
  2303. 7.24:    Must I free allocated memory before the program exits?
  2304.  
  2305. A:    You shouldn't have to.  A real operating system definitively
  2306.     reclaims all memory when a program exits.  Nevertheless, some
  2307.     personal computers are said not to reliably recover memory, and
  2308.     all that can be inferred from the ANSI/ISO C Standard is that
  2309.     this is a "quality of implementation issue."
  2310.  
  2311.     References: ANSI Sec. 4.10.3.2; ISO Sec. 7.10.3.2.
  2312.  
  2313. 7.25:    I have a program which mallocs and later frees a lot of memory,
  2314.     but memory usage (as reported by ps) doesn't seem to go back
  2315.     down.
  2316.  
  2317. A:    Most implementations of malloc/free do not return freed memory
  2318.     to the operating system (if there is one), but merely make it
  2319.     available for future malloc() calls within the same program.
  2320.  
  2321. 7.26:    How does free() know how many bytes to free?
  2322.  
  2323. A:    The malloc/free implementation remembers the size of each block
  2324.     allocated and returned, so it is not necessary to remind it of
  2325.     the size when freeing.
  2326.  
  2327. 7.27:    So can I query the malloc package to find out how big an
  2328.     allocated block is?
  2329.  
  2330. A:    Not portably.
  2331.  
  2332. 7.30:    Is it legal to pass a null pointer as the first argument to
  2333.     realloc()?  Why would you want to?
  2334.  
  2335. A:    ANSI C sanctions this usage (and the related realloc(..., 0),
  2336.     which frees), although several earlier implementations do not
  2337.     support it, so it may not be fully portable.  Passing an
  2338.     initially-null pointer to realloc() can make it easier to write
  2339.     a self-starting incremental allocation algorithm.
  2340.  
  2341.     References: ANSI Sec. 4.10.3.4; ISO Sec. 7.10.3.4; H&S Sec. 16.3
  2342.     p. 388.
  2343.  
  2344. 7.31:    What's the difference between calloc() and malloc()?  Is it safe
  2345.     to take advantage of calloc's zero-filling?  Does free() work
  2346.     on memory allocated with calloc(), or do you need a cfree()?
  2347.  
  2348. A:    calloc(m, n) is essentially equivalent to
  2349.  
  2350.         p = malloc(m * n);
  2351.         memset(p, 0, m * n);
  2352.  
  2353.     The zero fill is all-bits-zero, and does *not* therefore
  2354.     guarantee useful null pointer values (see section 5 of this
  2355.     list) or floating-point zero values.  free() is properly used to
  2356.     free the memory allocated by calloc().
  2357.  
  2358.     References: ANSI Sec. 4.10.3 to 4.10.3.2; ISO Sec. 7.10.3 to
  2359.     7.10.3.2; H&S Sec. 16.1 p. 386, Sec. 16.2 p. 386; PCS Sec. 11
  2360.     pp. 141,142.
  2361.  
  2362. 7.32:    What is alloca() and why is its use discouraged?
  2363.  
  2364. A:    alloca() allocates memory which is automatically freed when the
  2365.     function which called alloca() returns.  That is, memory
  2366.     allocated with alloca is local to a particular function's "stack
  2367.     frame" or context.
  2368.  
  2369.     alloca() cannot be written portably, and is difficult to
  2370.     implement on machines without a conventional stack.  Its use is
  2371.     problematical (and the obvious implementation on a stack-based
  2372.     machine fails) when its return value is passed directly to
  2373.     another function, as in fgets(alloca(100), 100, stdin).
  2374.  
  2375.     For these reasons, alloca() is not Standard and cannot be used
  2376.     in programs which must be widely portable, no matter how useful
  2377.     it might be.
  2378.  
  2379.     See also question 7.22.
  2380.  
  2381.     References: Rationale Sec. 4.10.3.
  2382.  
  2383.  
  2384. Section 8. Characters and Strings
  2385.  
  2386. 8.1:    Why doesn't
  2387.  
  2388.         strcat(string, '!');
  2389.  
  2390.     work?
  2391.  
  2392. A:    There is a very real difference between characters and strings,
  2393.     and strcat() concatenates *strings*.
  2394.  
  2395.     Characters in C are represented by small integers corresponding
  2396.     to their character set values (see also question 8.6 below).
  2397.     Strings are represented by arrays of characters; you usually
  2398.     manipulate a pointer to the first character of the array.  It is
  2399.     never correct to use one when the other is expected.  To append
  2400.     a ! to a string, use
  2401.  
  2402.         strcat(string, "!");
  2403.  
  2404.     See also questions 1.32, 7.2, and 16.6.
  2405.  
  2406.     References: CT&P Sec. 1.5 pp. 9-10.
  2407.  
  2408. 8.2:    I'm checking a string to see if it matches a particular value.
  2409.     Why isn't this code working?
  2410.  
  2411.         char *string;
  2412.         ...
  2413.         if(string == "value") {
  2414.             /* string matches "value" */
  2415.             ...
  2416.         }
  2417.  
  2418. A:    Strings in C are represented as arrays of characters, and C
  2419.     never manipulates (assigns, compares, etc.) arrays as a whole.
  2420.     The == operator in the code fragment above compares two pointers
  2421.     -- the value of the pointer variable string and a pointer to the
  2422.     string literal "value" -- to see if they are equal, that is, if
  2423.     they point to the same place.  They probably don't, so the
  2424.     comparison never succeeds.
  2425.  
  2426.     To compare two strings, you generally use the library function
  2427.     strcmp():
  2428.  
  2429.         if(strcmp(string, "value") == 0) {
  2430.             /* string matches "value" */
  2431.             ...
  2432.         }
  2433.  
  2434. 8.3:    If I can say
  2435.  
  2436.         char a[] = "Hello, world!";
  2437.  
  2438.     why can't I say
  2439.  
  2440.         char a[14];
  2441.         a = "Hello, world!";
  2442.  
  2443. A:    Strings are arrays, and you can't assign arrays directly.  Use
  2444.     strcpy() instead:
  2445.  
  2446.         strcpy(a, "Hello, world!");
  2447.  
  2448.     See also questions 1.32, 4.2, and 7.2.
  2449.  
  2450. 8.6:    How can I get the numeric (character set) value corresponding to
  2451.     a character, or vice versa?
  2452.  
  2453. A:    In C, characters are represented by small integers corresponding
  2454.     to their values (in the machine's character set), so you don't
  2455.     need a conversion routine: if you have the character, you have
  2456.     its value.
  2457.  
  2458. 8.9:    I think something's wrong with my compiler: I just noticed that
  2459.     sizeof('a') is 2, not 1 (i.e. not sizeof(char)).
  2460.  
  2461. A:    Perhaps surprisingly, character constants in C are of type int,
  2462.     so sizeof('a') is sizeof(int) (though it's different in C++).
  2463.     See also question 7.8.
  2464.  
  2465.     References: ANSI Sec. 3.1.3.4; ISO Sec. 6.1.3.4; H&S Sec. 2.7.3
  2466.     p. 29.
  2467.  
  2468.  
  2469. Section 9. Boolean Expressions
  2470.  
  2471. 9.1:    What is the right type to use for Boolean values in C?  Why
  2472.     isn't it a standard type?  Should I use #defines or enums for
  2473.     the true and false values?
  2474.  
  2475. A:    C does not provide a standard Boolean type, in part because
  2476.     picking one involves a space/time tradeoff which can best be
  2477.     decided by the programmer.  (Using an int may be faster, while
  2478.     using char may save data space.  Smaller types may make the
  2479.     generated code bigger or slower, though, if they require lots of
  2480.     conversions to and from int.)
  2481.  
  2482.     The choice between #defines and enumeration constants for the
  2483.     true/false values is arbitrary and not terribly interesting (see
  2484.     also questions 2.22 and 17.10).  Use any of
  2485.  
  2486.         #define TRUE  1            #define YES 1
  2487.         #define FALSE 0            #define NO  0
  2488.  
  2489.         enum bool {false, true};    enum bool {no, yes};
  2490.  
  2491.     or use raw 1 and 0, as long as you are consistent within one
  2492.     program or project.  (An enumeration may be preferable if your
  2493.     debugger shows the names of enumeration constants when examining
  2494.     variables.)
  2495.  
  2496.     Some people prefer variants like
  2497.  
  2498.         #define TRUE (1==1)
  2499.         #define FALSE (!TRUE)
  2500.  
  2501.     or define "helper" macros such as
  2502.  
  2503.         #define Istrue(e) ((e) != 0)
  2504.  
  2505.     These don't buy anything (see question 9.2 below; see also
  2506.     questions 5.12 and 10.2).
  2507.  
  2508. 9.2:    Isn't #defining TRUE to be 1 dangerous, since any nonzero value
  2509.     is considered "true" in C?  What if a built-in logical or
  2510.     relational operator "returns" something other than 1?
  2511.  
  2512. A:    It is true (sic) that any nonzero value is considered true in C,
  2513.     but this applies only "on input", i.e. where a Boolean value is
  2514.     expected.  When a Boolean value is generated by a built-in
  2515.     operator, it is guaranteed to be 1 or 0.  Therefore, the test
  2516.  
  2517.         if((a == b) == TRUE)
  2518.  
  2519.     would work as expected (as long as TRUE is 1), but it is
  2520.     obviously silly.  In general, explicit tests against TRUE and
  2521.     FALSE are inappropriate, because some library functions (notably
  2522.     isupper(), isalpha(), etc.) return, on success, a nonzero value
  2523.     which is *not* necessarily 1.  (Besides, if you believe that
  2524.     "if((a == b) == TRUE)" is an improvement over "if(a == b)", why
  2525.     stop there?  Why not use "if(((a == b) == TRUE) == TRUE)"?)  A
  2526.     good rule of thumb is to use TRUE and FALSE (or the like) only
  2527.     for assignment to a Boolean variable or function parameter, or
  2528.     as the return value from a Boolean function, but never in a
  2529.     comparison.
  2530.  
  2531.     The preprocessor macros TRUE and FALSE (and, of course, NULL)
  2532.     are used for code readability, not because the underlying values
  2533.     might ever change.  (See also questions 5.3 and 5.10.)
  2534.  
  2535.     On the other hand, Boolean values and definitions can evidently
  2536.     be confusing, and some programmers feel that TRUE and FALSE
  2537.     macros only compound the confusion.  (See also question 5.9.)
  2538.  
  2539.     References: K&R1 Sec. 2.6 p. 39, Sec. 2.7 p. 41; K&R2 Sec. 2.6
  2540.     p. 42, Sec. 2.7 p. 44, Sec. A7.4.7 p. 204, Sec. A7.9 p. 206;
  2541.     ANSI Sec. 3.3.3.3, Sec. 3.3.8, Sec. 3.3.9, Sec. 3.3.13,
  2542.     Sec. 3.3.14, Sec. 3.3.15, Sec. 3.6.4.1, Sec. 3.6.5; ISO
  2543.     Sec. 6.3.3.3, Sec. 6.3.8, Sec. 6.3.9, Sec. 6.3.13, Sec. 6.3.14,
  2544.     Sec. 6.3.15, Sec. 6.6.4.1, Sec. 6.6.5; H&S Sec. 7.5.4 pp. 196-7,
  2545.     Sec. 7.6.4 pp. 207-8, Sec. 7.6.5 pp. 208-9, Sec. 7.7 pp. 217-8,
  2546.     Sec. 7.8 pp. 218-9, Sec. 8.5 pp. 238-9, Sec. 8.6 pp. 241-4;
  2547.     "What the Tortoise Said to Achilles".
  2548.  
  2549. 9.3:    Is if(p), where p is a pointer, a valid conditional?
  2550.  
  2551. A:    Yes.  See question 5.3.
  2552.  
  2553.  
  2554. Section 10. C Preprocessor
  2555.  
  2556. 10.2:    Here are some cute preprocessor macros:
  2557.  
  2558.         #define begin    {
  2559.         #define end    }
  2560.  
  2561.     What do y'all think?
  2562.  
  2563. A:    Bleah.  See also section 17.
  2564.  
  2565. 10.3:    How can I write a generic macro to swap two values?
  2566.  
  2567. A:    There is no good answer to this question.  If the values are
  2568.     integers, a well-known trick using exclusive-OR could perhaps be
  2569.     used, but it will not work for floating-point values or
  2570.     pointers, or if the two values are the same variable (and the
  2571.     "obvious" supercompressed implementation for integral types
  2572.     a^=b^=a^=b is illegal due to multiple side-effects; see question
  2573.     3.2).  If the macro is intended to be used on values of
  2574.     arbitrary type (the usual goal), it cannot use a temporary,
  2575.     since it does not know what type of temporary it needs (and
  2576.     would have a hard time naming it if it did), and standard C does
  2577.     not provide a typeof operator.
  2578.  
  2579.     The best all-around solution is probably to forget about using a
  2580.     macro, unless you're willing to pass in the type as a third
  2581.     argument.
  2582.  
  2583. 10.4:    What's the best way to write a multi-statement macro?
  2584.  
  2585. A:    The usual goal is to write a macro that can be invoked as if it
  2586.     were a statement consisting of a single function call.  This
  2587.     means that the "caller" will be supplying the final semicolon,
  2588.     so the macro body should not.  The macro body cannot therefore
  2589.     be a simple brace-enclosed compound statement, because syntax
  2590.     errors would result if it were invoked (apparently as a single
  2591.     statement, but with a resultant extra semicolon) as the if
  2592.     branch of an if/else statement with an explicit else clause.
  2593.  
  2594.     The traditional solution, therefore, is to use
  2595.  
  2596.         #define MACRO(arg1, arg2) do {    \
  2597.             /* declarations */    \
  2598.             stmt1;            \
  2599.             stmt2;            \
  2600.             /* ... */        \
  2601.             } while(0)    /* (no trailing ; ) */
  2602.  
  2603.     When the caller appends a semicolon, this expansion becomes a
  2604.     single statement regardless of context.  (An optimizing compiler
  2605.     will remove any "dead" tests or branches on the constant
  2606.     condition 0, although lint may complain.)
  2607.  
  2608.     If all of the statements in the intended macro are simple
  2609.     expressions, with no declarations or loops, another technique is
  2610.     to write a single, parenthesized expression using one or more
  2611.     comma operators.  (For an example, see the first DEBUG() macro
  2612.     in question 10.26.)  This technique also allows a value to be
  2613.     "returned."
  2614.  
  2615.     References: H&S Sec. 3.3.2 p. 45; CT&P Sec. 6.3 pp. 82-3.
  2616.  
  2617. 10.6:    I'm splitting up a program into multiple source files for the
  2618.     first time, and I'm wondering what to put in .c files and what
  2619.     to put in .h files.  (What does ".h" mean, anyway?)
  2620.  
  2621. A:    As a general rule, you should put these things in header (.h)
  2622.     files:
  2623.  
  2624.         macro definitions (preprocessor #defines)
  2625.         structure, union, and enumeration declarations
  2626.         typedef declarations
  2627.         external function declarations (see also question 1.11)
  2628.         global variable declarations
  2629.  
  2630.     It's especially important to put a declaration or definition in
  2631.     a header file when it will be shared between several other
  2632.     files.  (In particular, never put external function prototypes
  2633.     in .c files.  See also question 1.7.)
  2634.  
  2635.     On the other hand, when a definition or declaration should
  2636.     remain private to one source file, it's fine to leave it there.
  2637.  
  2638.     See also questions 1.7 and 10.7.
  2639.  
  2640.     References: K&R2 Sec. 4.5 pp. 81-2; H&S Sec. 9.2.3 p. 267; CT&P
  2641.     Sec. 4.6 pp. 66-7.
  2642.  
  2643. 10.7:    Is it acceptable for one header file to #include another?
  2644.  
  2645. A:    It's a question of style, and thus receives considerable debate.
  2646.     Many people believe that "nested #include files" are to be
  2647.     avoided: the prestigious Indian Hill Style Guide (see question
  2648.     17.9) disparages them; they can make it harder to find relevant
  2649.     definitions; they can lead to multiple-definition errors if a
  2650.     file is #included twice; and they make manual Makefile
  2651.     maintenance very difficult.  On the other hand, they make it
  2652.     possible to use header files in a modular way (a header file can
  2653.     #include what it needs itself, rather than requiring each
  2654.     #includer to do so); a tool like grep (or a tags file) makes it
  2655.     easy to find definitions no matter where they are; a popular
  2656.     trick along the lines of:
  2657.  
  2658.         #ifndef HFILENAME_USED
  2659.         #define HFILENAME_USED
  2660.         ...header file contents...
  2661.         #endif
  2662.  
  2663.     (where a different bracketing macro name is used for each header
  2664.     file) makes a header file "idempotent" so that it can safely be
  2665.     #included multiple times; and automated Makefile maintenance
  2666.     tools (which are a virtual necessity in large projects anyway;
  2667.     see question 18.1) handle dependency generation in the face of
  2668.     nested #include files easily.  See also question 17.10.
  2669.  
  2670.     References: Rationale Sec. 4.1.2.
  2671.  
  2672. 10.8:    Where are header ("#include") files searched for?
  2673.  
  2674. A:    The exact behavior is implementation-defined (which means that
  2675.     it is supposed to be documented; see question 11.33).
  2676.     Typically, headers named with <> syntax are searched for in one
  2677.     or more standard places.  Header files named with "" syntax are
  2678.     first searched for in the "current directory," then (if not
  2679.     found) in the same standard places.
  2680.  
  2681.     Traditionally (especially under Unix compilers), the current
  2682.     directory is taken to be the directory containing the file
  2683.     containing the #include directive.  Under other compilers,
  2684.     however, the current directory (if any) is the directory in
  2685.     which the compiler was initially invoked.  Check your compiler
  2686.     documentation.
  2687.  
  2688.     References: K&R2 Sec. A12.4 p. 231; ANSI Sec. 3.8.2; ISO
  2689.     Sec. 6.8.2; H&S Sec. 3.4 p. 55.
  2690.  
  2691. 10.9:    I'm getting strange syntax errors on the very first declaration
  2692.     in a file, but it looks fine.
  2693.  
  2694. A:    Perhaps there's a missing semicolon at the end of the last
  2695.     declaration in the last header file you're #including.  See also
  2696.     questions 2.18 and 11.29.
  2697.  
  2698. 10.11:    I seem to be missing the system header file <sgtty.h>.  Can
  2699.     someone send me a copy?
  2700.  
  2701. A:    Standard headers exist in part so that definitions appropriate
  2702.     to your compiler, operating system, and processor can be
  2703.     supplied.  You cannot just pick up a copy of someone else's
  2704.     header file and expect it to work, unless that person is using
  2705.     exactly the same environment.  Ask your compiler vendor why the
  2706.     file was not provided (or to send a replacement copy).
  2707.  
  2708. 10.12:    How can I construct preprocessor #if expressions which compare
  2709.     strings?
  2710.  
  2711. A:    You can't do it directly; preprocessor #if arithmetic uses only
  2712.     integers.  You can #define several manifest constants, however,
  2713.     and implement  conditionals on those.
  2714.  
  2715.     See also question 20.17.
  2716.  
  2717.     References: K&R2 Sec. 4.11.3 p. 91; ANSI Sec. 3.8.1; ISO
  2718.     Sec. 6.8.1; H&S Sec. 7.11.1 p. 225.
  2719.  
  2720. 10.13:    Does the sizeof operator work in preprocessor #if directives?
  2721.  
  2722. A:    No.  Preprocessing happens during an earlier phase of
  2723.     compilation, before type names have been parsed.  Instead of
  2724.     sizeof, consider using the predefined constants in ANSI's
  2725.     <limits.h>, if applicable, or perhaps a "configure" script.
  2726.     (Better yet, try to write code which is inherently insensitive
  2727.     to type sizes.)
  2728.  
  2729.     References: ANSI Sec. 2.1.1.2, Sec. 3.8.1 footnote 83; ISO
  2730.     Sec. 5.1.1.2, Sec. 6.8.1; H&S Sec. 7.11.1 p. 225.
  2731.  
  2732. 10.14:    Can I use an #ifdef in a #define line, to define something two
  2733.     different ways?
  2734.  
  2735. A:    No.  You can't "run the preprocessor on itself," so to speak.
  2736.     What you can do is use one of two completely separate #define
  2737.     lines, depending on the #ifdef setting.
  2738.  
  2739.     References: ANSI Sec. 3.8.3, Sec. 3.8.3.4; ISO Sec. 6.8.3,
  2740.     Sec. 6.8.3.4; H&S Sec. 3.2 pp. 40-1.
  2741.  
  2742. 10.15:    Is there anything like an #ifdef for typedefs?
  2743.  
  2744. A:    Unfortunately, no.  (See also question 10.13.)
  2745.  
  2746.     References: ANSI Sec. 2.1.1.2, Sec. 3.8.1 footnote 83; ISO
  2747.     Sec. 5.1.1.2, Sec. 6.8.1; H&S Sec. 7.11.1 p. 225.
  2748.  
  2749. 10.16:    How can I use a preprocessor #if expression to tell if a machine
  2750.     is big-endian or little-endian?
  2751.  
  2752. A:    You probably can't.  (Preprocessor arithmetic uses only long
  2753.     integers, and there is no concept of addressing.  )  Are you
  2754.     sure you need to know the machine's endianness explicitly?
  2755.     Usually it's better to write code which doesn't care ).  See
  2756.     also question 20.9.
  2757.  
  2758.     References: ANSI Sec. 3.8.1; ISO Sec. 6.8.1; H&S Sec. 7.11.1
  2759.     p. 225.
  2760.  
  2761. 10.18:    I inherited some code which contains far too many #ifdef's for
  2762.     my taste.  How can I preprocess the code to leave only one
  2763.     conditional compilation set, without running it through the
  2764.     preprocessor and expanding all of the #include's and #define's
  2765.     as well?
  2766.  
  2767. A:    There are programs floating around called unifdef, rmifdef, and
  2768.     scpp ("selective C preprocessor") which do exactly this.  See
  2769.     question 18.16.
  2770.  
  2771. 10.19:    How can I list all of the pre#defined identifiers?
  2772.  
  2773. A:    There's no standard way, although it is a common need.  If the
  2774.     compiler documentation is unhelpful, the most expedient way is
  2775.     probably to extract printable strings from the compiler or
  2776.     preprocessor executable with something like the Unix strings
  2777.     utility.  Beware that many traditional system-specific
  2778.     pre#defined identifiers (e.g. "unix") are non-Standard (because
  2779.     they clash with the user's namespace) and are being removed or
  2780.     renamed.
  2781.  
  2782. 10.20:    I have some old code that tries to construct identifiers with a
  2783.     macro like
  2784.  
  2785.         #define Paste(a, b) a/**/b
  2786.  
  2787.     but it doesn't work any more.
  2788.  
  2789. A:    It was an undocumented feature of some early preprocessor
  2790.     implementations (notably John Reiser's) that comments
  2791.     disappeared entirely and could therefore be used for token
  2792.     pasting.  ANSI affirms (as did K&R1) that comments are replaced
  2793.     with white space.  However, since the need for pasting tokens
  2794.     was demonstrated and real, ANSI introduced a well-defined token-
  2795.     pasting operator, ##, which can be used like this:
  2796.  
  2797.         #define Paste(a, b) a##b
  2798.  
  2799.     See also question 11.17.
  2800.  
  2801.     References: ANSI Sec. 3.8.3.3; ISO Sec. 6.8.3.3; Rationale
  2802.     Sec. 3.8.3.3; H&S Sec. 3.3.9 p. 52.
  2803.  
  2804. 10.22:    Why is the macro
  2805.  
  2806.         #define TRACE(n) printf("TRACE: %d\n", n)
  2807.  
  2808.     giving me the warning "macro replacement within a string
  2809.     literal"?  It seems to be expanding
  2810.  
  2811.         TRACE(count);
  2812.     as
  2813.         printf("TRACE: %d\count", count);
  2814.  
  2815. A:    See question 11.18.
  2816.  
  2817. 10.23:    How can I use a macro argument inside a string literal in the
  2818.     macro expansion?
  2819.  
  2820. A:    See question 11.18.
  2821.  
  2822. 10.25:    I've got this tricky preprocessing I want to do and I can't
  2823.     figure out a way to do it.
  2824.  
  2825. A:    C's preprocessor is not intended as a general-purpose tool.
  2826.     (Note also that it is not guaranteed to be available as a
  2827.     separate program.)  Rather than forcing it to do something
  2828.     inappropriate, consider writing your own little special-purpose
  2829.     preprocessing tool, instead.  You can easily get a utility like
  2830.     make(1) to run it for you automatically.
  2831.  
  2832.     If you are trying to preprocess something other than C, consider
  2833.     using a general-purpose preprocessor.  (One older one available
  2834.     on most Unix systems is m4.)
  2835.  
  2836. 10.26:    How can I write a macro which takes a variable number of
  2837.     arguments?
  2838.  
  2839. A:    One popular trick is to define and invoke the macro with a
  2840.     single, parenthesized "argument" which in the macro expansion
  2841.     becomes the entire argument list, parentheses and all, for a
  2842.     function such as printf():
  2843.  
  2844.         #define DEBUG(args) (printf("DEBUG: "), printf args)
  2845.  
  2846.         if(n != 0) DEBUG(("n is %d\n", n));
  2847.  
  2848.     The obvious disadvantage is that the caller must always remember
  2849.     to use the extra parentheses.
  2850.  
  2851.     gcc has an extension which allows a function-like macro to
  2852.     accept a variable number of arguments, but it's not standard.
  2853.     Other possible solutions are to use different macros (DEBUG1,
  2854.     DEBUG2, etc.) depending on the number of arguments, to play
  2855.     games with commas:
  2856.  
  2857.         #define DEBUG(args) (printf("DEBUG: "), printf(args))
  2858.         #define _ ,
  2859.  
  2860.         DEBUG("i = %d" _ i)
  2861.  
  2862.     It is often better to use a bona-fide function, which can take a
  2863.     variable number of arguments in a well-defined way.  See
  2864.     questions 15.4 and 15.5.
  2865.  
  2866.  
  2867. Section 11.  ANSI/ISO Standard C
  2868.  
  2869. 11.1:    What is the "ANSI C Standard?"
  2870.  
  2871. A:    In 1983, the American National Standards Institute (ANSI)
  2872.     commissioned a committee, X3J11, to standardize the C language.
  2873.     After a long, arduous process, including several widespread
  2874.     public reviews, the committee's work was finally ratified as ANS
  2875.     X3.159-1989 on December 14, 1989, and published in the spring of
  2876.     1990.    For the most part, ANSI C standardizes existing practice,
  2877.     with a few additions from C++ (most notably function prototypes)
  2878.     and support for multinational character sets (including the
  2879.     controversial trigraph sequences).  The ANSI C standard also
  2880.     formalizes the C run-time library support routines.
  2881.  
  2882.     More recently, the Standard has been adopted as an international
  2883.     standard, ISO/IEC 9899:1990, and this ISO Standard replaces the
  2884.     earlier X3.159 even within the United States.  Its sections are
  2885.     numbered differently (briefly, ISO sections 5 through 7
  2886.     correspond roughly to the old ANSI sections 2 through 4).  As an
  2887.     ISO Standard, it is subject to ongoing revision through the
  2888.     release of Technical Corrigenda and Normative Addenda.
  2889.  
  2890.     In 1994, Technical Corrigendum 1 amended the Standard in about
  2891.     40 places, most of them minor corrections or clarifications.
  2892.     More recently, Normative Addendum 1 added about 50 pages of new
  2893.     material, mostly specifying new library functions for
  2894.     internationalization.  The production of Technical Corrigenda is
  2895.     an ongoing process, and a second one is expected in late 1995.
  2896.     In addition, both ANSI and ISO require periodic review of their
  2897.     standards.  This process is beginning in 1995, and will likely
  2898.     result in a completely revised standard (nicknamed "C9X," on the
  2899.     assumption of completion by 1999).
  2900.  
  2901.     The original ANSI Standard included a "Rationale," explaining
  2902.     many of its decisions, and discussing a number of subtle points,
  2903.     including several of those covered here.  (The Rationale was
  2904.     "not part of ANSI Standard X3.159-1989, but... included for
  2905.     information only," and is not included with the ISO Standard.)
  2906.  
  2907. 11.2:    How can I get a copy of the Standard?
  2908.  
  2909. A:    Copies are available in the United States from
  2910.  
  2911.         American National Standards Institute
  2912.         11 W. 42nd St., 13th floor
  2913.         New York, NY  10036  USA
  2914.         (+1) 212 642 4900
  2915.  
  2916.     and
  2917.  
  2918.         Global Engineering Documents
  2919.         15 Inverness Way E
  2920.         Englewood, CO  80112  USA
  2921.         (+1) 303 397 2715
  2922.         (800) 854 7179  (U.S. & Canada)
  2923.  
  2924.     In other countries, contact the appropriate national standards
  2925.     body, or ISO in Geneva at:
  2926.  
  2927.         ISO Sales
  2928.         Case Postale 56
  2929.         CH-1211 Geneve 20
  2930.         Switzerland
  2931.  
  2932.     (or see URL http://www.iso.ch or check the comp.std.internat FAQ
  2933.     list, Standards.Faq).
  2934.  
  2935.     At the time of this writing, the cost is $130.00 from ANSI or
  2936.     $410.00 from Global.  Copies of the original X3.159 (including
  2937.     the Rationale) may still be available at $205.00 from ANSI or
  2938.     $162.50 from Global.  Note that ANSI derives revenues to support
  2939.     its operations from the sale of printed standards, so electronic
  2940.     copies are *not* available.
  2941.  
  2942.     In the U.S., it may be possible to get a copy of the original
  2943.     ANSI X3.159 (including the Rationale) as "FIPS PUB 160" from
  2944.  
  2945.         National Technical Information Service (NTIS)
  2946.         U.S. Department of Commerce
  2947.         Springfield, VA  22161
  2948.         703 487 4650
  2949.  
  2950.     The mistitled _Annotated ANSI C Standard_, with annotations by
  2951.     Herbert Schildt, contains most of the text of ISO 9899; it is
  2952.     published by Osborne/McGraw-Hill, ISBN 0-07-881952-0, and sells
  2953.     in the U.S. for approximately $40.  It has been suggested that
  2954.     the price differential between this work and the official
  2955.     standard reflects the value of the annotations: they are plagued
  2956.     by numerous errors and omissions, and a few pages of the
  2957.     Standard itself are missing.  Many people on the net recommend
  2958.     ignoring the annotations entirely.  A review of the annotations
  2959.     ("annotated annotations") by Clive Feather can be found on the
  2960.     web at http://www.lysator.liu.se/c/schildt.html .
  2961.  
  2962.     The text of the Rationale (not the full Standard) can be
  2963.     obtained by anonymous ftp from ftp.uu.net (see question 18.16)
  2964.     in directory doc/standards/ansi/X3.159-1989, and is also
  2965.     available on the web at
  2966.     http://www.lysator.liu.se/c/rat/title.html .  The Rationale has
  2967.     also been printed by Silicon Press, ISBN 0-929306-07-4.
  2968.  
  2969. 11.3:    My ANSI compiler complains about a mismatch when it sees
  2970.  
  2971.         extern int func(float);
  2972.  
  2973.         int func(x)
  2974.         float x;
  2975.         { ...
  2976.  
  2977. A:    You have mixed the new-style prototype declaration
  2978.     "extern int func(float);" with the old-style definition
  2979.     "int func(x) float x;".  It is usually safe to mix the two
  2980.     styles (see question 11.4), but not in this case.
  2981.  
  2982.     Old C (and ANSI C, in the absence of prototypes, and in variable-
  2983.     length argument lists; see question 15.2) "widens" certain
  2984.     arguments when they are passed to functions.  floats are
  2985.     promoted to double, and characters and short integers are
  2986.     promoted to int.  (For old-style function definitions, the
  2987.     values are automatically converted back to the corresponding
  2988.     narrower types within the body of the called function, if they
  2989.     are declared that way there.)
  2990.  
  2991.     This problem can be fixed either by using new-style syntax
  2992.     consistently in the definition:
  2993.  
  2994.         int func(float x) { ... }
  2995.  
  2996.     or by changing the new-style prototype declaration to match the
  2997.     old-style definition:
  2998.  
  2999.         extern int func(double);
  3000.  
  3001.     (In this case, it would be clearest to change the old-style
  3002.     definition to use double as well, as long as the address of that
  3003.     parameter is not taken.)
  3004.  
  3005.     It may also be safer to avoid "narrow" (char, short int, and
  3006.     float) function arguments and return types altogether.
  3007.  
  3008.     See also question 1.25.
  3009.  
  3010.     References: K&R1 Sec. A7.1 p. 186; K&R2 Sec. A7.3.2 p. 202; ANSI
  3011.     Sec. 3.3.2.2, Sec. 3.5.4.3; ISO Sec. 6.3.2.2, Sec. 6.5.4.3;
  3012.     Rationale Sec. 3.3.2.2, Sec. 3.5.4.3; H&S Sec. 9.2 pp. 265-7,
  3013.     Sec. 9.4 pp. 272-3.
  3014.  
  3015. 11.4:    Can you mix old-style and new-style function syntax?
  3016.  
  3017. A:    Doing so is perfectly legal, as long as you're careful (see
  3018.     especially question 11.3).  Note however that old-style syntax
  3019.     is marked as obsolescent, so official support for it may be
  3020.     removed some day.
  3021.  
  3022.     References: ANSI Sec. 3.7.1, Sec. 3.9.5; ISO Sec. 6.7.1,
  3023.     Sec. 6.9.5; H&S Sec. 9.2.2 pp. 265-7, Sec. 9.2.5 pp. 269-70.
  3024.  
  3025. 11.5:    Why does the declaration
  3026.  
  3027.         extern f(struct x *p);
  3028.  
  3029.     give me an obscure warning message about "struct x introduced in
  3030.     prototype scope"?
  3031.  
  3032. A:    In a quirk of C's normal block scoping rules, a structure
  3033.     declared (or even mentioned) for the first time within a
  3034.     prototype cannot be compatible with other structures declared in
  3035.     the same source file (it goes out of scope at the end of the
  3036.     prototype).
  3037.  
  3038.     To resolve the problem, precede the prototype with the vacuous-
  3039.     looking declaration
  3040.  
  3041.         struct x;
  3042.  
  3043.     which places an (incomplete) declaration of struct x at file
  3044.     scope, so that all following declarations involving struct x can
  3045.     at least be sure they're referring to the same struct x.
  3046.  
  3047.     References: ANSI Sec. 3.1.2.1, Sec. 3.1.2.6, Sec. 3.5.2.3; ISO
  3048.     Sec. 6.1.2.1, Sec. 6.1.2.6, Sec. 6.5.2.3.
  3049.  
  3050. 11.8:    I don't understand why I can't use const values in initializers
  3051.     and array dimensions, as in
  3052.  
  3053.         const int n = 5;
  3054.         int a[n];
  3055.  
  3056. A:    The const qualifier really means "read-only;" an object so
  3057.     qualified is a run-time object which cannot (normally) be
  3058.     assigned to.  The value of a const-qualified object is therefore
  3059.     *not* a constant expression in the full sense of the term.  (C
  3060.     is unlike C++ in this regard.)  When you need a true compile-
  3061.     time constant, use a preprocessor #define.
  3062.  
  3063.     References: ANSI Sec. 3.4; ISO Sec. 6.4; H&S Secs. 7.11.2,7.11.3
  3064.     pp. 226-7.
  3065.  
  3066. 11.9:    What's the difference between "const char *p" and
  3067.     "char * const p"?
  3068.  
  3069. A:    "char const *p" declares a pointer to a constant character (you
  3070.     can't change the character); "char * const p" declares a
  3071.     constant pointer to a (variable) character (i.e. you can't
  3072.     change the pointer).
  3073.  
  3074.     Read these "inside out" to understand them; see also question
  3075.     1.21.
  3076.  
  3077.     References: ANSI Sec. 3.5.4.1 examples; ISO Sec. 6.5.4.1;
  3078.     Rationale Sec. 3.5.4.1; H&S Sec. 4.4.4 p. 81.
  3079.  
  3080. 11.10:    Why can't I pass a char ** to a function which expects a
  3081.     const char **?
  3082.  
  3083. A:    You can use a pointer-to-T (for any type T) where a pointer-to-
  3084.     const-T is expected.  However, the rule (an explicit exception)
  3085.     which permits slight mismatches in qualified pointer types is
  3086.     not applied recursively, but only at the top level.
  3087.  
  3088.     You must use explicit casts (e.g. (const char **) in this case)
  3089.     when assigning (or passing) pointers which have qualifier
  3090.     mismatches at other than the first level of indirection.
  3091.  
  3092.     References: ANSI Sec. 3.1.2.6, Sec. 3.3.16.1, Sec. 3.5.3; ISO
  3093.     Sec. 6.1.2.6, Sec. 6.3.16.1, Sec. 6.5.3; H&S Sec. 7.9.1 pp. 221-
  3094.     2.
  3095.  
  3096. 11.12:    Can I declare main() as void, to shut off these annoying "main
  3097.     returns no value" messages?
  3098.  
  3099. A:    No.  main() must be declared as returning an int, and as taking
  3100.     either zero or two arguments, of the appropriate types.  If
  3101.     you're calling exit() but still getting warnings, you may have
  3102.     to insert a redundant return statement (or use some kind of "not
  3103.     reached" directive, if available).
  3104.  
  3105.     Declaring a function as void does not merely shut off or
  3106.     rearrange warnings: it may also result in a different function
  3107.     call/return sequence, incompatible with what the caller (in
  3108.     main's case, the C run-time startup code) expects.
  3109.  
  3110.     (Note that this discussion of main() pertains only to "hosted"
  3111.     implementations; none of it applies to "freestanding"
  3112.     implementations, which may not even have main().  However,
  3113.     freestanding implementations are comparatively rare, and if
  3114.     you're using one, you probably know it.  If you've never heard
  3115.     of the distinction, you're probably using a hosted
  3116.     implementation, and the above rules apply.)
  3117.  
  3118.     References: ANSI Sec. 2.1.2.2.1, Sec. F.5.1; ISO Sec. 5.1.2.2.1,
  3119.     Sec. G.5.1; H&S Sec. 20.1 p. 416; CT&P Sec. 3.10 pp. 50-51.
  3120.  
  3121. 11.13:    But what about main's third argument, envp?
  3122.  
  3123. A:    It's a non-standard (though common) extension.  If you really
  3124.     need to access the environment in ways beyind what the standard
  3125.     getenv() function provides, though, the global variable environ
  3126.     is probably a better avenue (though it's equally non-standard).
  3127.  
  3128.     References: ANSI Sec. F.5.1; ISO Sec. G.5.1; H&S Sec. 20.1 pp.
  3129.     416-7.
  3130.  
  3131. 11.14:    I believe that declaring void main() can't fail, since I'm
  3132.     calling exit() instead of returning, and anyway my operating
  3133.     system ignores a program's exit/return status.
  3134.  
  3135. A:    It doesn't matter whether main() returns or not, or whether
  3136.     anyone looks at the status; the problem is that when main() is
  3137.     misdeclared, its caller (the runtime startup code) may not even
  3138.     be able to *call* it correctly (due to the potential clash of
  3139.     calling conventions; see question 11.12).  Your operating system
  3140.     may ignore the exit status, and void main() may work for you,
  3141.     but it is not portable and not correct.
  3142.  
  3143. 11.15:    The book I've been using, _C Programing for the Compleat Idiot_,
  3144.     always uses void main().
  3145.  
  3146. A:    Perhaps its author counts himself among the target audience.
  3147.     Many books unaccountably use void main() in examples.  They're
  3148.     wrong.
  3149.  
  3150. 11.16:    Is exit(status) truly equivalent to returning the same status
  3151.     from main()?
  3152.  
  3153. A:    Yes and no.  The Standard says that they are equivalent.
  3154.     However, a few older, nonconforming systems may have problems
  3155.     with one or the other form.  Also, a return from main() cannot
  3156.     be expected to work if data local to main() might be needed
  3157.     during cleanup; see also question 16.4.  (Finally, the two forms
  3158.     are obviously not equivalent in a recursive call to main().)
  3159.  
  3160.     References: K&R2 Sec. 7.6 pp. 163-4; ANSI Sec. 2.1.2.2.3; ISO
  3161.     Sec. 5.1.2.2.3.
  3162.  
  3163. 11.17:    I'm trying to use the ANSI "stringizing" preprocessing operator
  3164.     `#' to insert the value of a symbolic constant into a message,
  3165.     but it keeps stringizing the macro's name rather than its value.
  3166.  
  3167. A:    You can use something like the following two-step procedure to
  3168.     force a macro to be expanded as well as stringized:
  3169.  
  3170.         #define Str(x) #x
  3171.         #define Xstr(x) Str(x)
  3172.         #define OP plus
  3173.         char *opname = Xstr(OP);
  3174.  
  3175.     This code sets opname to "plus" rather than "OP".
  3176.  
  3177.     An equivalent circumlocution is necessary with the token-pasting
  3178.     operator ## when the values (rather than the names) of two
  3179.     macros are to be concatenated.
  3180.  
  3181.     References: ANSI Sec. 3.8.3.2, Sec. 3.8.3.5 example; ISO
  3182.     Sec. 6.8.3.2, Sec. 6.8.3.5.
  3183.  
  3184. 11.18:    What does the message "warning: macro replacement within a
  3185.     string literal" mean?
  3186.  
  3187. A:    Some pre-ANSI compilers/preprocessors interpreted macro
  3188.     definitions like
  3189.  
  3190.         #define TRACE(var, fmt) printf("TRACE: var = fmt\n", var)
  3191.  
  3192.     such that invocations like
  3193.  
  3194.         TRACE(i, %d);
  3195.  
  3196.     were expanded as
  3197.  
  3198.         printf("TRACE: i = %d\n", i);
  3199.  
  3200.     In other words, macro parameters were expanded even inside
  3201.     string literals and character constants.
  3202.  
  3203.     Macro expansion is *not* defined in this way by K&R or by
  3204.     Standard C.  When you do want to turn macro arguments into
  3205.     strings, you can use the new # preprocessing operator, along
  3206.     with string literal concatenation (another new ANSI feature):
  3207.  
  3208.         #define TRACE(var, fmt) \
  3209.             printf("TRACE: " #var " = " #fmt "\n", var)
  3210.  
  3211.     See also question 11.17 above.
  3212.  
  3213.     References: H&S Sec. 3.3.8 p. 51.
  3214.  
  3215. 11.19:    I'm getting strange syntax errors inside lines I've #ifdeffed
  3216.     out.
  3217.  
  3218. A:    Under ANSI C, the text inside a "turned off" #if, #ifdef, or
  3219.     #ifndef must still consist of "valid preprocessing tokens."
  3220.     This means that there must be no newlines inside quotes, and no
  3221.     unterminated comments or quotes (note particularly that an
  3222.     apostrophe within a contracted word looks like the beginning of
  3223.     a character constant).  Therefore, natural-language comments and
  3224.     pseudocode should always be written between the "official"
  3225.     comment delimiters /* and */.  (But see question 20.20, and also
  3226.     10.25.)
  3227.  
  3228.     References: ANSI Sec. 2.1.1.2, Sec. 3.1; ISO Sec. 5.1.1.2,
  3229.     Sec. 6.1; H&S Sec. 3.2 p. 40.
  3230.  
  3231. 11.20:    What are #pragmas and what are they good for?
  3232.  
  3233. A:    The #pragma directive provides a single, well-defined "escape
  3234.     hatch" which can be used for all sorts of implementation-
  3235.     specific controls and extensions: source listing control,
  3236.     structure packing, warning suppression (like lint's old
  3237.     /* NOTREACHED */ comments), etc.
  3238.  
  3239.     References: ANSI Sec. 3.8.6; ISO Sec. 6.8.6; H&S Sec. 3.7 p. 61.
  3240.  
  3241. 11.21:    What does "#pragma once" mean?  I found it in some header files.
  3242.  
  3243. A:    It is an extension implemented by some preprocessors to help
  3244.     make header files idempotent; it is essentially equivalent to
  3245.     the #ifndef trick mentioned in question 10.7.
  3246.  
  3247. 11.22:    Is char a[3] = "abc"; legal?  What does it mean?
  3248.  
  3249. A:    It is legal in ANSI C (and perhaps in a few pre-ANSI systems),
  3250.     though useful only in rare circumstances.  It declares an array
  3251.     of size three, initialized with the three characters 'a', 'b',
  3252.     and 'c', *without* the usual terminating '\0' character.  The
  3253.     array is therefore not a true C string and cannot be used with
  3254.     strcpy, printf %s, etc.
  3255.  
  3256.     Most of the time, you should let the compiler count the
  3257.     initializers when initializing arrays (in the case of the
  3258.     initializer "abc", of course, the computed size will be 4).
  3259.  
  3260.     References: ANSI Sec. 3.5.7; ISO Sec. 6.5.7; H&S Sec. 4.6.4 p.
  3261.     98.
  3262.  
  3263. 11.24:    Why can't I perform arithmetic on a void * pointer?
  3264.  
  3265. A:    The compiler doesn't know the size of the pointed-to objects.
  3266.     Before performing arithmetic, convert the pointer either to
  3267.     char * or to the pointer type you're trying to manipulate (but
  3268.     see also question 4.5).
  3269.  
  3270.     References: ANSI Sec. 3.1.2.5, Sec. 3.3.6; ISO Sec. 6.1.2.5,
  3271.     Sec. 6.3.6; H&S Sec. 7.6.2 p. 204.
  3272.  
  3273. 11.25:    What's the difference between memcpy() and memmove()?
  3274.  
  3275. A:    memmove() offers guaranteed behavior if the source and
  3276.     destination arguments overlap.  memcpy() makes no such
  3277.     guarantee, and may therefore be more efficiently implementable.
  3278.     When in doubt, it's safer to use memmove().
  3279.  
  3280.     References: K&R2 Sec. B3 p. 250; ANSI Sec. 4.11.2.1,
  3281.     Sec. 4.11.2.2; ISO Sec. 7.11.2.1, Sec. 7.11.2.2; Rationale
  3282.     Sec. 4.11.2; H&S Sec. 14.3 pp. 341-2; PCS Sec. 11 pp. 165-6.
  3283.  
  3284. 11.26:    What should malloc(0) do?  Return a null pointer or a pointer to
  3285.     0 bytes?
  3286.  
  3287. A:    The ANSI/ISO Standard says that it may do either; the behavior
  3288.     is implementation-defined (see question 11.33).
  3289.  
  3290.     References: ANSI Sec. 4.10.3; ISO Sec. 7.10.3; PCS Sec. 16.1 p.
  3291.     386.
  3292.  
  3293. 11.27:    Why does the ANSI Standard not guarantee more than six case-
  3294.     insensitive characters of external identifier significance?
  3295.  
  3296. A:    The problem is older linkers which are under the control of
  3297.     neither the ANSI/ISO Standard nor the C compiler developers on
  3298.     the systems which have them.  The limitation is only that
  3299.     identifiers be *significant* in the first six characters, not
  3300.     that they be restricted to six characters in length.  This
  3301.     limitation is annoying, but certainly not unbearable, and is
  3302.     marked in the Standard as "obsolescent," i.e. a future revision
  3303.     will likely relax it.
  3304.  
  3305.     This concession to current, restrictive linkers really had to be
  3306.     made, no matter how vehemently some people oppose it.  (The
  3307.     Rationale notes that its retention was "most painful.")  If you
  3308.     disagree, or have thought of a trick by which a compiler
  3309.     burdened with a restrictive linker could present the C
  3310.     programmer with the appearance of more significance in external
  3311.     identifiers, read the excellently-worded section 3.1.2 in the
  3312.     X3.159 Rationale (see question 11.1), which discusses several
  3313.     such schemes and explains why they could not be mandated.
  3314.  
  3315.     References: ANSI Sec. 3.1.2, Sec. 3.9.1; ISO Sec. 6.1.2,
  3316.     Sec. 6.9.1; Rationale Sec. 3.1.2; H&S Sec. 2.5 pp. 22-3.
  3317.  
  3318. 11.29:    My compiler is rejecting the simplest possible test programs,
  3319.     with all kinds of syntax errors.
  3320.  
  3321. A:    Perhaps it is a pre-ANSI compiler, unable to accept function
  3322.     prototypes and the like.
  3323.  
  3324.     See also questions 1.31, 10.9, and 11.30.
  3325.  
  3326. 11.30:    Why are some ANSI/ISO Standard library routines showing up as
  3327.     undefined, even though I've got an ANSI compiler?
  3328.  
  3329. A:    It's possible to have a compiler available which accepts ANSI
  3330.     syntax, but not to have ANSI-compatible header files or run-time
  3331.     libraries installed.  (In fact, this situation is rather common
  3332.     when using a non-vendor-supplied compiler such as gcc.)  See
  3333.     also questions 11.29, 13.25, and 13.26.
  3334.  
  3335. 11.31:    Does anyone have a tool for converting old-style C programs to
  3336.     ANSI C, or vice versa, or for automatically generating
  3337.     prototypes?
  3338.  
  3339. A:    Two programs, protoize and unprotoize, convert back and forth
  3340.     between prototyped and "old style" function definitions and
  3341.     declarations.  (These programs do *not* handle full-blown
  3342.     translation between "Classic" C and ANSI C.)  These programs are
  3343.     part of the FSF's GNU C compiler distribution; see question
  3344.     18.3.
  3345.  
  3346.     The unproto program (/pub/unix/unproto5.shar.Z on
  3347.     ftp.win.tue.nl) is a filter which sits between the preprocessor
  3348.     and the next compiler pass, converting most of ANSI C to
  3349.     traditional C on-the-fly.
  3350.  
  3351.     The GNU GhostScript package comes with a little program called
  3352.     ansi2knr.
  3353.  
  3354.     Before converting ANSI C back to old-style, beware that such a
  3355.     conversion cannot always be made both safely and automatically.
  3356.     ANSI C introduces new features and complexities not found in K&R
  3357.     C.  You'll especially need to be careful of prototyped function
  3358.     calls; you'll probably need to insert explicit casts.  See also
  3359.     questions 11.3 and 11.29.
  3360.  
  3361.     Several prototype generators exist, many as modifications to
  3362.     lint.  A program called CPROTO was posted to comp.sources.misc
  3363.     in March, 1992.  There is another program called "cextract."
  3364.     Many vendors supply simple utilities like these with their
  3365.     compilers.  See also question 18.16.  (But be careful when
  3366.     generating prototypes for old functions with "narrow"
  3367.     parameters; see question 11.3.)
  3368.  
  3369.     Finally, are you sure you really need to convert lots of old
  3370.     code to ANSI C?  The old-style function syntax is still
  3371.     acceptable, and a hasty conversion can easily introduce bugs.
  3372.     (See question 11.3.)
  3373.  
  3374. 11.32:    Why won't the Frobozz Magic C Compiler, which claims to be ANSI
  3375.     compliant, accept this code?  I know that the code is ANSI,
  3376.     because gcc accepts it.
  3377.  
  3378. A:    Many compilers support a few non-Standard extensions, gcc more
  3379.     so than most.  Are you sure that the code being rejected doesn't
  3380.     rely on such an extension?  It is usually a bad idea to perform
  3381.     experiments with a particular compiler to determine properties
  3382.     of a language; the applicable standard may permit variations, or
  3383.     the compiler may be wrong.  See also question 11.35.
  3384.  
  3385. 11.33:    People seem to make a point of distinguishing between
  3386.     implementation-defined, unspecified, and undefined behavior.
  3387.     What's the difference?
  3388.  
  3389. A:    Briefly: implementation-defined means that an implementation
  3390.     must choose some behavior and document it.  Unspecified means
  3391.     that an implementation should choose some behavior, but need not
  3392.     document it.  Undefined means that absolutely anything might
  3393.     happen.  In no case does the Standard impose requirements; in
  3394.     the first two cases it occasionally suggests (and may require a
  3395.     choice from among) a small set of likely behaviors.
  3396.  
  3397.     Note that since the Standard imposes *no* requirements on the
  3398.     behavior of a compiler faced with an instance of undefined
  3399.     behavior, the compiler can do absolutely anything.  In
  3400.     particular, there is no guarantee that the rest of the program
  3401.     will perform normally.  It's perilous to think that you can
  3402.     tolerate undefined behavior in a program; see question 3.2 for a
  3403.     relatively simple example.
  3404.  
  3405.     If you're interested in writing portable code, you can ignore
  3406.     the distinctions, as you'll want to avoid code that depends on
  3407.     any of the three behaviors.
  3408.  
  3409.     See also questions 3.9, and 11.34.
  3410.  
  3411.     References: ANSI Sec. 1.6; ISO Sec. 3.10, Sec. 3.16, Sec. 3.17;
  3412.     Rationale Sec. 1.6.
  3413.  
  3414. 11.34:    I'm appalled that the ANSI Standard leaves so many issues
  3415.     undefined.  Isn't a Standard's whole job to standardize these
  3416.     things?
  3417.  
  3418. A:    It has always been a characteristic of C that certain constructs
  3419.     behaved in whatever way a particular compiler or a particular
  3420.     piece of hardware chose to implement them.  This deliberate
  3421.     imprecision often allows compilers to generate more efficient
  3422.     code for common cases, without having to burden all programs
  3423.     with extra code to assure well-defined behavior of cases deemed
  3424.     to be less reasonable.  Therefore, the Standard is simply
  3425.     codifying existing practice.
  3426.  
  3427.     A programming language standard can be thought of as a treaty
  3428.     between the language user and the compiler implementor.  Parts
  3429.     of that treaty consist of features which the compiler
  3430.     implementor agrees to provide, and which the user may assume
  3431.     will be available.  Other parts, however, consist of rules which
  3432.     the user agrees to follow and which the implementor may assume
  3433.     will be followed.  As long as both sides uphold their
  3434.     guarantees, programs have a fighting chance of working
  3435.     correctly.  If *either* side reneges on any of its commitments,
  3436.     nothing is guaranteed to work.
  3437.  
  3438.     See also question 11.35.
  3439.  
  3440.     References: Rationale Sec. 1.1.
  3441.  
  3442. 11.35:    People keep saying that the behavior of i = i++ is undefined,
  3443.     but I just tried it on an ANSI-conforming compiler, and got the
  3444.     results I expected.
  3445.  
  3446. A:    A compiler may do anything it likes when faced with undefined
  3447.     behavior (and, within limits, with implementation-defined and
  3448.     unspecified behavior), including doing what you expect.  It's
  3449.     unwise to depend on it, though.  See also questions 11.32,
  3450.     11.33, and 11.34.
  3451.  
  3452.  
  3453. Section 12. Stdio
  3454.  
  3455. 12.1:    What's wrong with this code?
  3456.  
  3457.         char c;
  3458.         while((c = getchar()) != EOF) ...
  3459.  
  3460. A:    For one thing, the variable to hold getchar's return value
  3461.     must be an int.  getchar() can return all possible character
  3462.     values, as well as EOF.  By passing getchar's return value
  3463.     through a char, either a normal character might be
  3464.     misinterpreted as EOF, or the EOF might be altered (particularly
  3465.     if type char is unsigned) and so never seen.
  3466.  
  3467.     References: K&R1 Sec. 1.5 p. 14; K&R2 Sec. 1.5.1 p. 16; ANSI
  3468.     Sec. 3.1.2.5, Sec. 4.9.1, Sec. 4.9.7.5; ISO Sec. 6.1.2.5,
  3469.     Sec. 7.9.1, Sec. 7.9.7.5; H&S Sec. 5.1.3 p. 116, Sec. 15.1,
  3470.     Sec. 15.6; CT&P Sec. 5.1 p. 70; PCS Sec. 11 p. 157.
  3471.  
  3472. 12.2:    Why does the code
  3473.  
  3474.         while(!feof(infp)) {
  3475.             fgets(buf, MAXLINE, infp);
  3476.             fputs(buf, outfp);
  3477.         }
  3478.  
  3479.     copy the last line twice?
  3480.  
  3481. A:    In C, EOF is only indicated *after* an input routine has tried
  3482.     to read, and has reached end-of-file.  (In other words, C's I/O
  3483.     is not like Pascal's.)  Usually, you should just check the
  3484.     return value of the input routine (fgets() in this case); often,
  3485.     you don't need to use feof() at all.
  3486.  
  3487.     References: K&R2 Sec. 7.6 p. 164; ANSI Sec. 4.9.3, Sec. 4.9.7.1,
  3488.     Sec. 4.9.10.2; ISO Sec. 7.9.3, Sec. 7.9.7.1, Sec. 7.9.10.2; H&S
  3489.     Sec. 15.14 p. 382.
  3490.  
  3491. 12.4:    My program's prompts and intermediate output don't always show
  3492.     up on the screen, especially when I pipe the output through
  3493.     another program.
  3494.  
  3495. A:    It's best to use an explicit fflush(stdout) whenever output
  3496.     should definitely be visible.  Several mechanisms attempt to
  3497.     perform the fflush() for you, at the "right time," but they tend
  3498.     to apply only when stdout is an interactive terminal.  (See also
  3499.     question 12.24.)
  3500.  
  3501.     References: ANSI Sec. 4.9.5.2; ISO Sec. 7.9.5.2.
  3502.  
  3503. 12.5:    How can I read one character at a time, without waiting for the
  3504.     RETURN key?
  3505.  
  3506. A:    See question 19.1.
  3507.  
  3508. 12.6:    How can I print a '%' character in a printf format string?  I
  3509.     tried \%, but it didn't work.
  3510.  
  3511. A:    Simply double the percent sign: %% .
  3512.  
  3513.     \% can't work, because the backslash \ is the *compiler's*
  3514.     escape character, while here our problem is that the % is
  3515.     printf's escape character.
  3516.  
  3517.     See also question 19.17.
  3518.  
  3519.     References: K&R1 Sec. 7.3 p. 147; K&R2 Sec. 7.2 p. 154; ANSI
  3520.     Sec. 4.9.6.1; ISO Sec. 7.9.6.1.
  3521.  
  3522. 12.9:    Someone told me it was wrong to use %lf with printf().  How can
  3523.     printf() use %f for type double, if scanf() requires %lf?
  3524.  
  3525. A:    It's true that printf's %f specifier works with both float and
  3526.     double arguments.  Due to the "default argument promotions"
  3527.     (which apply in variable-length argument lists such as
  3528.     printf's, whether or not prototypes are in scope), values of
  3529.     type float are promoted to double, and printf() therefore sees
  3530.     only doubles.  See also questions 12.13 and 15.2.
  3531.  
  3532.     References: K&R1 Sec. 7.3 pp. 145-47, Sec. 7.4 pp. 147-50; K&R2
  3533.     Sec. 7.2 pp. 153-44, Sec. 7.4 pp. 157-59; ANSI Sec. 4.9.6.1,
  3534.     Sec. 4.9.6.2; ISO Sec. 7.9.6.1, Sec. 7.9.6.2; H&S Sec. 15.8 pp.
  3535.     357-64, Sec. 15.11 pp. 366-78; CT&P Sec. A.1 pp. 121-33.
  3536.  
  3537. 12.10:    How can I implement a variable field width with printf?  That
  3538.     is, instead of %8d, I want the width to be specified at run
  3539.     time.
  3540.  
  3541. A:    printf("%*d", width, n) will do just what you want.  See also
  3542.     question 12.15.
  3543.  
  3544.     References: K&R1 Sec. 7.3; K&R2 Sec. 7.2; ANSI Sec. 4.9.6.1; ISO
  3545.     Sec. 7.9.6.1; H&S Sec. 15.11.6; CT&P Sec. A.1.
  3546.  
  3547. 12.11:    How can I print numbers with commas separating the thousands?
  3548.     What about currency formatted numbers?
  3549.  
  3550. A:    The routines in <locale.h> begin to provide some support for
  3551.     these operations, but there is no standard routine for doing
  3552.     either task.  (The only thing printf() does in response to a
  3553.     custom locale setting is to change its decimal-point character.)
  3554.  
  3555.     References: ANSI Sec. 4.4; ISO Sec. 7.4; H&S Sec. 11.6 pp. 301-4.
  3556.  
  3557. 12.12:    Why doesn't the call scanf("%d", i) work?
  3558.  
  3559. A:    The arguments you pass to scanf() must always be pointers.
  3560.     To fix the fragment above, change it to scanf("%d", &i) .
  3561.  
  3562. 12.13:    Why doesn't this code:
  3563.  
  3564.         double d;
  3565.         scanf("%f", &d);
  3566.  
  3567.     work?
  3568.  
  3569. A:    Unlike printf(), scanf() uses %lf for values of type double, and
  3570.     %f for float.  See also question 12.9.
  3571.  
  3572. 12.15:    How can I specify a variable width in a scanf() format string?
  3573.  
  3574. A:    You can't; an asterisk in a scanf() format string means to
  3575.     suppress assignment.  You may be able to use ANSI stringizing
  3576.     and string concatenation to accomplish about the same thing, or
  3577.     to construct a scanf format string on-the-fly.
  3578.  
  3579. 12.17:    When I read numbers from the keyboard with scanf "%d\n", it
  3580.     seems to hang until I type one extra line of input.
  3581.  
  3582. A:    Perhaps surprisingly, \n in a scanf format string does *not*
  3583.     mean to expect a newline, but rather to read and discard
  3584.     characters as long as each is a whitespace character.  See also
  3585.     question 12.20.
  3586.  
  3587.     References: K&R2 Sec. B1.3 pp. 245-6; ANSI Sec. 4.9.6.2; ISO
  3588.     Sec. 7.9.6.2; H&S Sec. 15.8 pp. 357-64.
  3589.  
  3590. 12.18:    I'm reading a number with scanf %d and then a string with
  3591.     gets(), but the compiler seems to be skipping the call to
  3592.     gets()!
  3593.  
  3594. A:    scanf %d won't consume a trailing newline.  If the input number
  3595.     is immediately followed by a newline, that newline will
  3596.     immediately satisfy the gets().
  3597.  
  3598.     As a general rule, you shouldn't try to interlace calls to
  3599.     scanf() with calls to gets() (or any other input routines);
  3600.     scanf's peculiar treatment of newlines almost always leads to
  3601.     trouble.  Either use scanf() to read everything or nothing.
  3602.  
  3603.     See also questions 12.20 and 12.23.
  3604.  
  3605.     References: ANSI Sec. 4.9.6.2; ISO Sec. 7.9.6.2; H&S Sec. 15.8
  3606.     pp. 357-64.
  3607.  
  3608. 12.19:    I figured I could use scanf() more safely if I checked its
  3609.     return value to make sure that the user typed the numeric values
  3610.     I expect, but sometimes it seems to go into an infinite loop.
  3611.  
  3612. A:    When scanf() is attempting to convert numbers, any non-numeric
  3613.     characters it encounters terminate the conversion *and are left
  3614.     on the input stream*.  Therefore, unless some other steps are
  3615.     taken, unexpected non-numeric input "jams" scanf() again and
  3616.     again: scanf() never gets past the bad character(s) to encounter
  3617.     later, valid data.  If the user types a character like `x' in
  3618.     response to a numeric scanf format such as %d or %f, code that
  3619.     simply re-prompts and retries the same scanf() call will
  3620.     immediately reencounter the same `x'.
  3621.  
  3622.     See also question 12.20.
  3623.  
  3624.     References: ANSI Sec. 4.9.6.2; ISO Sec. 7.9.6.2; H&S Sec. 15.8
  3625.     pp. 357-64.
  3626.  
  3627. 12.20:    Why does everyone say not to use scanf()?  What should I use
  3628.     instead?
  3629.  
  3630. A:    scanf() has a number of problems -- see questions 12.17, 12.18,
  3631.     and 12.19.  Also, its %s format has the same problem that gets()
  3632.     has (see question 12.23) -- it's hard to guarantee that the
  3633.     receiving buffer won't overflow.
  3634.  
  3635.     More generally, scanf() is designed for relatively structured,
  3636.     formatted input (its name is in fact derived from "scan
  3637.     formatted").  If you pay attention, it will tell you whether it
  3638.     succeeded or failed, but it can tell you only approximately
  3639.     where it failed, and not at all how or why.  It's nearly
  3640.     impossible to do decent error recovery with scanf(); usually
  3641.     it's far easier to read entire lines (with fgets() or the like),
  3642.     then interpret them, either using sscanf() or some other
  3643.     techniques.  (Routines like strtol(), strtok(), and atoi() are
  3644.     often useful; see also question 13.6.)  If you do use sscanf(),
  3645.     don't forget to check the return value to make sure that the
  3646.     expected number of items were found.
  3647.  
  3648.     References: K&R2 Sec. 7.4 p. 159.
  3649.  
  3650. 12.21:    How can I tell how much destination buffer space I'll need for
  3651.     an arbitrary sprintf call?  How can I avoid overflowing the
  3652.     destination buffer with sprintf()?
  3653.  
  3654. A:    There are not (yet) any good answers to either of these
  3655.     excellent questions, and this represents perhaps the biggest
  3656.     deficiency in the traditional stdio library.
  3657.  
  3658.     When the format string being used with sprintf() is known and
  3659.     relatively simple, you can usually predict a buffer size in an
  3660.     ad-hoc way.  If the format consists of one or two %s's, you can
  3661.     count the fixed characters in the format string yourself (or let
  3662.     sizeof count them for you) and add in the result of calling
  3663.     strlen() on the string(s) to be inserted.  You can
  3664.     conservatively estimate the size that %d will expand to with
  3665.     code like:
  3666.  
  3667.         #include <limits.h>
  3668.         char buf[(sizeof(int) * CHAR_BIT + 2) / 3 + 1 + 1];
  3669.         sprintf(buf, "%d", n);
  3670.  
  3671.     (This code computes the number of characters required for a base-
  3672.     8 representation of a number; a base-10 expansion is guaranteed
  3673.     to take as much room or less.)
  3674.  
  3675.     When the format string is more complicated, or is not even known
  3676.     until run time, predicting the buffer size becomes as difficult
  3677.     as reimplementing sprintf(), and correspondingly error-prone
  3678.     (and inadvisable).  A last-ditch technique which is sometimes
  3679.     suggested is to use fprintf() to print the same text to a bit
  3680.     bucket or temporary file, and then to look at fprintf's return
  3681.     value or the size of the file (but see question 19.12).
  3682.  
  3683.     If there's any chance that the buffer might not be big enough,
  3684.     you won't want to call sprintf() without some guarantee that the
  3685.     buffer will not overflow and overwrite some other part of
  3686.     memory.  Several stdio's (including GNU and 4.4bsd) provide the
  3687.     obvious snprintf() function, which can be used like this:
  3688.  
  3689.         snprintf(buf, bufsize, "You typed \"%s\"", answer);
  3690.  
  3691.     and we can hope that a future revision of the ANSI/ISO C
  3692.     Standard will include this function.
  3693.  
  3694. 12.23:    Why does everyone say not to use gets()?
  3695.  
  3696. A:    Unlike fgets(), gets() cannot be told the size of the buffer
  3697.     it's to read into, so it cannot be prevented from overflowing
  3698.     that buffer.  As a general rule, always use fgets().  See
  3699.     question 7.1 for a code fragment illustrating the replacement of
  3700.     gets() with fgets().
  3701.  
  3702.     References: Rationale Sec. 4.9.7.2; H&S Sec. 15.7 p. 356.
  3703.  
  3704. 12.24:    Why does errno contain ENOTTY after a call to printf()?
  3705.  
  3706. A:    Many implementations of the stdio package adjust their behavior
  3707.     slightly if stdout is a terminal.  To make the determination,
  3708.     these implementations perform some operation which happens to
  3709.     fail (with ENOTTY) if stdout is not a terminal.  Although the
  3710.     output operation goes on to complete successfully, errno still
  3711.     contains ENOTTY.  (Note that it is only meaningful for a program
  3712.     to inspect the contents of errno after an error has been
  3713.     reported.)
  3714.  
  3715.     References: ANSI Sec. 4.1.3, Sec. 4.9.10.3; ISO Sec. 7.1.4,
  3716.     Sec. 7.9.10.3; CT&P Sec. 5.4 p. 73; PCS Sec. 14 p. 254.
  3717.  
  3718. 12.25:    What's the difference between fgetpos/fsetpos and ftell/fseek?
  3719.     What are fgetpos() and fsetpos() good for?
  3720.  
  3721. A:    fgetpos() and fsetpos() use a special typedef, fpos_t, for
  3722.     representing offsets (positions) in a file.  The type behind
  3723.     this typedef, if chosen appropriately, can represent arbitrarily
  3724.     large offsets, allowing fgetpos() and fsetpos() to be used with
  3725.     arbitrarily huge files.  ftell() and fseek(), on the other hand,
  3726.     use long int, and are therefore limited to offsets which can be
  3727.     represented in a long int.  See also question 1.4.
  3728.  
  3729.     References: K&R2 Sec. B1.6 p. 248; ANSI Sec. 4.9.1,
  3730.     Secs. 4.9.9.1,4.9.9.3; ISO Sec. 7.9.1, Secs. 7.9.9.1,7.9.9.3;
  3731.     H&S Sec. 15.5 p. 252.
  3732.  
  3733. 12.26:    How can I flush pending input so that a user's typeahead isn't
  3734.     read at the next prompt?  Will fflush(stdin) work?
  3735.  
  3736. A:    fflush() is defined only for output streams.  Since its
  3737.     definition of "flush" is to complete the writing of buffered
  3738.     characters (not to discard them), discarding unread input would
  3739.     not be an analogous meaning for fflush on input streams.
  3740.  
  3741.     There is no standard way to discard unread characters from a
  3742.     stdio input stream, nor would such a way be sufficient unread
  3743.     characters can also accumulate in other, OS-level input buffers.
  3744.  
  3745.     References: ANSI Sec. 4.9.5.2; ISO Sec. 7.9.5.2; H&S Sec. 15.2.
  3746.  
  3747. 12.30:    I'm trying to update a file in place, by using fopen mode "r+",
  3748.     reading a certain string, and writing back a modified string,
  3749.     but it's not working.
  3750.  
  3751. A:    Be sure to call fseek before you write, both to seek back to the
  3752.     beginning of the string you're trying to overwrite, and because
  3753.     an fseek or fflush is always required between reading and
  3754.     writing in the read/write "+" modes.  Also, remember that you
  3755.     can only overwrite characters with the same number of
  3756.     replacement characters; see also question 19.14.
  3757.  
  3758.     References: ANSI Sec. 4.9.5.3; ISO Sec. 7.9.5.3.
  3759.  
  3760. 12.33:    How can I redirect stdin or stdout to a file from within a
  3761.     program?
  3762.  
  3763. A:    Use freopen() (but see question 12.34 below).
  3764.  
  3765.     References: ANSI Sec. 4.9.5.4; ISO Sec. 7.9.5.4; H&S Sec. 15.2.
  3766.  
  3767. 12.34:    Once I've used freopen(), how can I get the original stdout (or
  3768.     stdin) back?
  3769.  
  3770. A:    There isn't a good way.  If you need to switch back, the best
  3771.     solution is not to have used freopen() in the first place.  Try
  3772.     using your own explicit output (or input) stream variable, which
  3773.     you can reassign at will, while leaving the original stdout (or
  3774.     stdin) undisturbed.
  3775.  
  3776. 12.38:    How can I read a binary data file properly?  I'm occasionally
  3777.     seeing 0x0a and 0x0d values getting garbled, and it seems to hit
  3778.     EOF prematurely if the data contains the value 0x1a.
  3779.  
  3780. A:    When you're reading a binary data file, you should specify "rb"
  3781.     mode when calling fopen(), to make sure that text file
  3782.     translations do not occur.  Similarly, when writing binary data
  3783.     files, use "wb".
  3784.  
  3785.     Note that the text/binary distinction is made when you open the
  3786.     file: once a file is open, it doesn't matter which I/O calls you
  3787.     use on it.  See also question 20.5.
  3788.  
  3789.     References: ANSI Sec. 4.9.5.3; ISO Sec. 7.9.5.3; H&S Sec. 15.2.1
  3790.     p. 348.
  3791.  
  3792.  
  3793. Section 13. Library Functions
  3794.  
  3795. 13.1:    How can I convert numbers to strings (the opposite of atoi)?  Is
  3796.     there an itoa function?
  3797.  
  3798. A:    Just use sprintf().  (Don't worry that sprintf() may be
  3799.     overkill, potentially wasting run time or code space; it works
  3800.     well in practice.)  See the examples in the answer to question
  3801.     7.5; see also question 12.21.
  3802.  
  3803.     You can obviously use sprintf() to convert long or floating-
  3804.     point numbers to strings as well (using %ld or %f).
  3805.  
  3806.     References: K&R1 Sec. 3.6 p. 60; K&R2 Sec. 3.6 p. 64.
  3807.  
  3808. 13.2:    Why does strncpy() not always place a '\0' terminator in the
  3809.     destination string?
  3810.  
  3811. A:    strncpy() was first designed to handle a now-obsolete data
  3812.     structure, the fixed-length, not-necessarily-\0-terminated
  3813.     "string."  (A related quirk of strncpy's is that it pads short
  3814.     strings with multiple \0's, out to the specified length.)
  3815.     strncpy() is admittedly a bit cumbersome to use in other
  3816.     contexts, since you must often append a '\0' to the destination
  3817.     string by hand.  You can get around the problem by using
  3818.     strncat() instead of strncpy(): if the destination string starts
  3819.     out empty, strncat() does what you probably wanted strncpy() to
  3820.     do.  Another possibility is sprintf(dest, "%.*s", n, source) .
  3821.  
  3822.     When arbitrary bytes (as opposed to strings) are being copied,
  3823.     memcpy() is usually a more appropriate routine to use than
  3824.     strncpy().
  3825.  
  3826. 13.5:    Why do some versions of toupper() act strangely if given an
  3827.     upper-case letter?
  3828.     Why does some code call islower() before toupper()?
  3829.  
  3830. A:    Older versions of toupper() and tolower() did not always work
  3831.     correctly on arguments which did not need converting (i.e. on
  3832.     digits or punctuation or letters already of the desired case).
  3833.     In ANSI/ISO Standard C, these functions are guaranteed to work
  3834.     appropriately on all character arguments.
  3835.  
  3836.     References: ANSI Sec. 4.3.2; ISO Sec. 7.3.2; H&S Sec. 12.9 pp.
  3837.     320-1; PCS p. 182.
  3838.  
  3839. 13.6:    How can I split up a string into whitespace-separated fields?
  3840.     How can I duplicate the process by which main() is handed argc
  3841.     and argv?
  3842.  
  3843. A:    The only Standard routine available for this kind of
  3844.     "tokenizing" is strtok, although it can be tricky to use and it
  3845.     may not do everything you want it to.  (For instance, it does
  3846.     not handle quoting.)
  3847.  
  3848.     References: K&R2 Sec. B3 p. 250; ANSI Sec. 4.11.5.8; ISO
  3849.     Sec. 7.11.5.8; H&S Sec. 13.7 pp. 333-4; PCS p. 178.
  3850.  
  3851. 13.7:    I need some code to do regular expression and wildcard matching.
  3852.  
  3853. A:    Make sure you recognize the difference between classic regular
  3854.     expressions (variants of which are used in such Unix utilities
  3855.     as ed and grep), and filename wildcards (variants of which are
  3856.     used by most operating systems).
  3857.  
  3858.     There are a number of packages available for matching regular
  3859.     expressions.  Most packages use a pair of functions, one for
  3860.     "compiling" the regular expression, and one for "executing" it
  3861.     (i.e. matching strings against it).  Look for header files named
  3862.     <regex.h> or <regexp.h>, and functions called regcmp()/regex(),
  3863.     regcomp()/regexec(), or re_comp()/re_exec().  (These functions
  3864.     may exist in a separate regexp library.)  A popular, freely-
  3865.     redistributable regexp package by Henry Spencer is available
  3866.     from ftp.cs.toronto.edu in pub/regexp.shar.Z or in several other
  3867.     archives.  The GNU project has a package called rx.  See also
  3868.     question 18.16.
  3869.  
  3870.     Filename wildcard matching (sometimes called "globbing") is done
  3871.     in a variety of ways on different systems.  On Unix, wildcards
  3872.     are automatically expanded by the shell before a process is
  3873.     invoked, so programs rarely have to worry about them explicitly.
  3874.     Under MS-DOS compilers, there is often a special object file
  3875.     which can be linked in to a program to expand wildcards while
  3876.     argv is being built.  Several systems (including MS-DOS and VMS)
  3877.     provide system services for listing or opening files specified
  3878.     by wildcards.  Check your compiler/library documentation.
  3879.  
  3880. 13.8:    I'm trying to sort an array of strings with qsort(), using
  3881.     strcmp() as the comparison function, but it's not working.
  3882.  
  3883. A:    By "array of strings" you probably mean "array of pointers to
  3884.     char."  The arguments to qsort's comparison function are
  3885.     pointers to the objects being sorted, in this case, pointers to
  3886.     pointers to char.  strcmp(), however, accepts simple pointers to
  3887.     char.  Therefore, strcmp() can't be used directly.  Write an
  3888.     intermediate comparison function like this:
  3889.  
  3890.         /* compare strings via pointers */
  3891.         int pstrcmp(const void *p1, const void *p2)
  3892.         {
  3893.             return strcmp(*(char * const *)p1, *(char * const *)p2);
  3894.         }
  3895.  
  3896.     The comparison function's arguments are expressed as "generic
  3897.     pointers," const void *.  They are converted back to what they
  3898.     "really are" (char **) and dereferenced, yielding char *'s which
  3899.     can be passed to strcmp().  (Under a pre-ANSI compiler, declare
  3900.     the pointer parameters as char * instead of void *, and drop the
  3901.     consts.)
  3902.  
  3903.     (Don't be misled by the discussion in K&R2 Sec. 5.11 pp. 119-20,
  3904.     which is not discussing the Standard library's qsort).
  3905.  
  3906.     References: ANSI Sec. 4.10.5.2; ISO Sec. 7.10.5.2; H&S Sec. 20.5
  3907.     p. 419.
  3908.  
  3909. 13.9:    Now I'm trying to sort an array of structures with qsort().  My
  3910.     comparison function takes pointers to structures, but the
  3911.     compiler complains that the function is of the wrong type for
  3912.     qsort().  How can I cast the function pointer to shut off the
  3913.     warning?
  3914.  
  3915. A:    The conversions must be in the comparison function, which must
  3916.     be declared as accepting "generic pointers" (const void *) as
  3917.     discussed in question 13.8 above.  The comparison function might
  3918.     look like
  3919.  
  3920.         int mystructcmp(const void *p1, const void *p2)
  3921.         {
  3922.             const struct mystruct *sp1 = p1;
  3923.             const struct mystruct *sp2 = p2;
  3924.             /* now compare sp1->whatever and sp2-> ... */
  3925.  
  3926.     (The conversions from generic pointers to struct mystruct
  3927.     pointers happen in the initializations sp1 = p1 and sp2 = p2;
  3928.     the compiler performs the conversions implicitly since p1 and p2
  3929.     are void pointers.  Explicit casts, and char * pointers, would
  3930.     be required under a pre-ANSI compiler.  See also question 7.7.)
  3931.  
  3932.     If, on the other hand, you're sorting pointers to structures,
  3933.     you'll need indirection, as in question 13.8:
  3934.     sp1 = *(struct mystruct **)p1 .
  3935.  
  3936.     In general, it is a bad idea to insert casts just to "shut the
  3937.     compiler up."  Compiler warnings are usually trying to tell you
  3938.     something, and unless you really know what you're doing, you
  3939.     ignore or muzzle them at your peril.  See also question 4.9.
  3940.  
  3941.     References: ANSI Sec. 4.10.5.2; ISO Sec. 7.10.5.2; H&S Sec. 20.5
  3942.     p. 419.
  3943.  
  3944. 13.10:    How can I sort a linked list?
  3945.  
  3946. A:    Sometimes it's easier to keep the list in order as you build it
  3947.     (or perhaps to use a tree instead).  Algorithms like insertion
  3948.     sort and merge sort lend themselves ideally to use with linked
  3949.     lists.  If you want to use a standard library function, you can
  3950.     allocate a temporary array of pointers, fill it in with pointers
  3951.     to all your list nodes, call qsort(), and finally rebuild the
  3952.     list pointers based on the sorted array.
  3953.  
  3954.     References: Knuth Sec. 5.2.1 pp. 80-102, Sec. 5.2.4 pp. 159-168;
  3955.     Sedgewick Sec. 8 pp. 98-100, Sec. 12 pp. 163-175.
  3956.  
  3957. 13.11:    How can I sort more data than will fit in memory?
  3958.  
  3959. A:    You want an "external sort," which you can read about in Knuth,
  3960.     Volume 3.  The basic idea is to sort the data in chunks (as much
  3961.     as will fit in memory at one time), write each sorted chunk to a
  3962.     temporary file, and then merge the files.  Your operating system
  3963.     may provide a general-purpose sort utility, and if so, you can
  3964.     try invoking it from within your program: see questions 19.27
  3965.     and 19.30.
  3966.  
  3967.     References: Knuth Sec. 5.4 pp. 247-378; Sedgewick Sec. 13 pp.
  3968.     177-187.
  3969.  
  3970. 13.12:    How can I get the current date or time of day in a C program?
  3971.  
  3972. A:    Just use the time, ctime, and/or localtime functions.  (These
  3973.     routines have been around for years, and are in the ANSI
  3974.     standard.)  Here is a simple example:
  3975.  
  3976.         #include <stdio.h>
  3977.         #include <time.h>
  3978.  
  3979.         main()
  3980.         {
  3981.             time_t now;
  3982.             time(&now);
  3983.             printf("It's %.24s.\n", ctime(&now));
  3984.             return 0;
  3985.         }
  3986.  
  3987.     References: K&R2 Sec. B10 pp. 255-7; ANSI Sec. 4.12; ISO
  3988.     Sec. 7.12; H&S Sec. 18.
  3989.  
  3990. 13.13:    I know that the library routine localtime() will convert a
  3991.     time_t into a broken-down struct tm, and that ctime() will
  3992.     convert a time_t to a printable string.  How can I perform the
  3993.     inverse operations of converting a struct tm or a string into a
  3994.     time_t?
  3995.  
  3996. A:    ANSI C specifies a library routine, mktime(), which converts a
  3997.     struct tm to a time_t.
  3998.  
  3999.     Converting a string to a time_t is harder, because of the wide
  4000.     variety of date and time formats which might be encountered.
  4001.     Some systems provide a strptime() function, which is basically
  4002.     the inverse of strftime().  Other popular routines are partime()
  4003.     (widely distributed with the RCS package) and getdate() (and a
  4004.     few others, from the C news distribution).  See question 18.16.
  4005.  
  4006.     References: K&R2 Sec. B10 p. 256; ANSI Sec. 4.12.2.3; ISO
  4007.     Sec. 7.12.2.3; H&S Sec. 18.4 pp. 401-2.
  4008.  
  4009. 13.14:    How can I add N days to a date?  How can I find the difference
  4010.     between two dates?
  4011.  
  4012. A:    The ANSI/ISO Standard C mktime() and difftime() functions
  4013.     provide some support for both problems.  mktime() accepts non-
  4014.     normalized dates, so it is straightforward to take a filled-in
  4015.     struct tm, add or subtract from the tm_mday field, and call
  4016.     mktime() to normalize the year, month, and day fields (and
  4017.     incidentally convert to a time_t value).  difftime() computes
  4018.     the difference, in seconds, between two time_t values; mktime()
  4019.     can be used to compute time_t values for two dates to be
  4020.     subtracted.
  4021.  
  4022.     These solutions are only guaranteed to work correctly for dates
  4023.     in the range which can be represented as time_t's.  The tm_mday
  4024.     field is an int, so day offsets of more than 32,736 or so may
  4025.     cause overflow.  Note also that at daylight saving time
  4026.     changeovers, local days are not 24 hours long.
  4027.  
  4028.     Another approach to both problems is to use "Julian day"
  4029.     numbers.  Implementations of Julian day routines can be found in
  4030.     the file JULCAL10.ZIP from the Simtel/Oakland archives (see
  4031.     question 18.16) and the "Date conversions" article mentioned in
  4032.     the References.
  4033.  
  4034.     See also questions 13.13, 20.31, and 20.32.
  4035.  
  4036.     References: K&R2 Sec. B10 p. 256; ANSI Secs. 4.12.2.2,4.12.2.3;
  4037.     ISO Secs. 7.12.2.2,7.12.2.3; H&S Secs. 18.4,18.5 pp. 401-2;
  4038.     David Burki, "Date Conversions".
  4039.  
  4040. 13.15:    I need a random number generator.
  4041.  
  4042. A:    The Standard C library has one: rand().  The implementation on
  4043.     your system may not be perfect, but writing a better one isn't
  4044.     necessarily easy, either.
  4045.  
  4046.     If you do find yourself needing to implement your own random
  4047.     number generator, there is plenty of literature out there; see
  4048.     the References.  There are also any number of packages on the
  4049.     net: look for r250, RANLIB, and FSULTRA (see question 18.16).
  4050.  
  4051.     References: K&R2 Sec. 2.7 p. 46, Sec. 7.8.7 p. 168; ANSI
  4052.     Sec. 4.10.2.1; ISO Sec. 7.10.2.1; H&S Sec. 17.7 p. 393; PCS
  4053.     Sec. 11 p. 172; Knuth Vol. 2 Chap. 3 pp. 1-177; Park and Miller,
  4054.     "Random Number Generators: Good Ones are hard to Find".
  4055.  
  4056. 13.16:    How can I get random integers in a certain range?
  4057.  
  4058. A:    The obvious way,
  4059.  
  4060.         rand() % N        /* POOR */
  4061.  
  4062.     (which tries to return numbers from 0 to N-1) is poor, because
  4063.     the low-order bits of many random number generators are
  4064.     distressingly *non*-random.  (See question 13.18.)  A better
  4065.     method is something like
  4066.  
  4067.         (int)((double)rand() / ((double)RAND_MAX + 1) * N)
  4068.  
  4069.     If you're worried about using floating point, you could use
  4070.  
  4071.         rand() / (RAND_MAX / N + 1)
  4072.  
  4073.     Both methods obviously require knowing RAND_MAX (which ANSI
  4074.     #defines in <stdlib.h>), and assume that N is much less than
  4075.     RAND_MAX.
  4076.  
  4077.     (Note, by the way, that RAND_MAX is a *constant* telling you
  4078.     what the fixed range of the C library rand() function is.  You
  4079.     cannot set RAND_MAX to some other value, and there is no way of
  4080.     requesting that rand() return numbers in some other range.)
  4081.  
  4082.     If you're starting with a random number generator which returns
  4083.     floating-point values between 0 and 1, all you have to do to get
  4084.     integers from 0 to N-1 is multiply the output of that generator
  4085.     by N.
  4086.  
  4087.     References: K&R2 Sec. 7.8.7 p. 168; PCS Sec. 11 p. 172.
  4088.  
  4089. 13.17:    Each time I run my program, I get the same sequence of numbers
  4090.     back from rand().
  4091.  
  4092. A:    You can call srand() to seed the pseudo-random number generator
  4093.     with a truly random initial value.  Popular seed values are the
  4094.     time of day, or the elapsed time before the user presses a key
  4095.     (although keypress times are hard to determine portably; see
  4096.     question 19.37).  (Note also that it's rarely useful to call
  4097.     srand() more than once during a run of a program; in particular,
  4098.     don't try calling srand() before each call to rand(), in an
  4099.     attempt to get "really random" numbers.)
  4100.  
  4101.     References: K&R2 Sec. 7.8.7 p. 168; ANSI Sec. 4.10.2.2; ISO
  4102.     Sec. 7.10.2.2; H&S Sec. 17.7 p. 393.
  4103.  
  4104. 13.18:    I need a random true/false value, so I'm just taking rand() % 2,
  4105.     but it's alternating 0, 1, 0, 1, 0...
  4106.  
  4107. A:    Poor pseudorandom number generators (such as the ones
  4108.     unfortunately supplied with some systems) are not very random in
  4109.     the low-order bits.  Try using the higher-order bits: see
  4110.     question 13.16.
  4111.  
  4112.     References: Knuth Sec. 3.2.1.1 pp. 12-14.
  4113.  
  4114. 13.20:    How can I generate random numbers with a normal or Gaussian
  4115.     distribution?
  4116.  
  4117. A:    Here is one method, by Box and Muller, and recommended by Knuth:
  4118.  
  4119.         #include <stdlib.h>
  4120.         #include <math.h>
  4121.  
  4122.         double gaussrand()
  4123.         {
  4124.             static double V1, V2, S;
  4125.             static int phase = 0;
  4126.             double X;
  4127.  
  4128.             if(phase == 0) {
  4129.                 do {
  4130.                     double U1 = (double)rand() / RAND_MAX;
  4131.                     double U2 = (double)rand() / RAND_MAX;
  4132.  
  4133.                     V1 = 2 * U1 - 1;
  4134.                     V2 = 2 * U2 - 1;
  4135.                     S = V1 * V1 + V2 * V2;
  4136.                     } while(S >= 1 || S == 0);
  4137.  
  4138.                 X = V1 * sqrt(-2 * log(S) / S);
  4139.             } else
  4140.                 X = V2 * sqrt(-2 * log(S) / S);
  4141.  
  4142.             phase = 1 - phase;
  4143.  
  4144.             return X;
  4145.         }
  4146.  
  4147.     See the extended versions of this list (see question 20.40) for
  4148.     other ideas.
  4149.  
  4150.     References: Knuth Sec. 3.4.1 p. 117; Box and Muller, "A Note on
  4151.     the Generation of Random Normal Deviates"; Press et al.,
  4152.     _Numerical Recipes in C_ Sec. 7.2 pp. 288-290.
  4153.  
  4154. 13.24:    I'm trying to port this         A:    Those routines are variously
  4155.     old program.  Why do I        obsolete; you should
  4156.     get "undefined external"    instead:
  4157.     errors for:
  4158.  
  4159.     index?                use strchr.
  4160.     rindex?                use strrchr.
  4161.     bcopy?                use memmove, after
  4162.                     interchanging the first and
  4163.                     second arguments (see also
  4164.                     question 11.25).
  4165.     bcmp?                use memcmp.
  4166.     bzero?                use memset, with a second
  4167.                     argument of 0.
  4168.  
  4169.     Contrariwise, if you're using an older system which is missing
  4170.     the functions in the second column, you may be able to implement
  4171.     them in terms of, or substitute, the functions in the first.
  4172.  
  4173.     References: PCS Sec. 11.
  4174.  
  4175. 13.25:    I keep getting errors due to library functions being undefined,
  4176.     but I'm #including all the right header files.
  4177.  
  4178. A:    In some cases (especially if the functions are nonstandard) you
  4179.     may have to explicitly ask for the correct libraries to be
  4180.     searched when you link the program.  See also questions 11.30,
  4181.     13.26, and 14.3.
  4182.  
  4183. 13.26:    I'm still getting errors due to library functions being
  4184.     undefined, even though I'm explicitly requesting the right
  4185.     libraries while linking.
  4186.  
  4187. A:    Many linkers make one pass over the list of object files and
  4188.     libraries you specify, and extract from libraries only those
  4189.     modules which satisfy references which have so far come up as
  4190.     undefined.  Therefore, the order in which libraries are listed
  4191.     with respect to object files (and each other) is significant;
  4192.     usually, you want to search the libraries last.  (For example,
  4193.     under Unix, put any -l options towards the end of the command
  4194.     line.)  See also question 13.28.
  4195.  
  4196. 13.28:    What does it mean when the linker says that _end is undefined?
  4197.  
  4198. A:    That message is a quirk of the old Unix linkers.  You only get
  4199.     an error about _end being undefined when other things are
  4200.     undefined, too -- fix the others, and the error about _end will
  4201.     disappear.  (See also questions 13.25 and 13.26.)
  4202.  
  4203.  
  4204. Section 14. Floating Point
  4205.  
  4206. 14.1:    When I set a float variable to, say, 3.1, why is printf()
  4207.     printing it as 3.0999999?
  4208.  
  4209. A:    Most computers use base 2 for floating-point numbers as well as
  4210.     for integers.  In base 2, 1/1010 (that is, 1/10 decimal) is an
  4211.     infinitely-repeating fraction: its binary representation is
  4212.     0.0001100110011... .  Depending on how carefully your compiler's
  4213.     binary/decimal conversion routines (such as those used by
  4214.     printf) have been written, you may see discrepancies when
  4215.     numbers (especially low-precision floats) not exactly
  4216.     representable in base 2 are assigned or read in and then printed
  4217.     (i.e. converted from base 10 to base 2 and back again).  See
  4218.     also question 14.6.
  4219.  
  4220. 14.2:    I'm trying to take some square roots, but I'm getting crazy
  4221.     numbers.
  4222.  
  4223. A:    Make sure that you have #included <math.h>, and correctly
  4224.     declared other functions returning double.  (Another library
  4225.     routine to be careful with is atof(), which is declared in
  4226.     <stdlib.h>.)  See also question 14.3 below.
  4227.  
  4228.     References: CT&P Sec. 4.5 pp. 65-6.
  4229.  
  4230. 14.3:    I'm trying to do some simple trig, and I am #including <math.h>,
  4231.     but I keep getting "undefined: sin" compilation errors.
  4232.  
  4233. A:    Make sure you're actually linking with the math library.  For
  4234.     instance, under Unix, you usually need to use the -lm option, at
  4235.     the *end* of the command line, when compiling/linking.  See also
  4236.     questions 13.25 and 13.26.
  4237.  
  4238. 14.4:    My floating-point calculations are acting strangely and giving
  4239.     me different answers on different machines.
  4240.  
  4241. A:    First, see question 14.2 above.
  4242.  
  4243.     If the problem isn't that simple, recall that digital computers
  4244.     usually use floating-point formats which provide a close but by
  4245.     no means exact simulation of real number arithmetic.  Underflow,
  4246.     cumulative precision loss, and other anomalies are often
  4247.     troublesome.
  4248.  
  4249.     Don't assume that floating-point results will be exact, and
  4250.     especially don't assume that floating-point values can be
  4251.     compared for equality.  (Don't throw haphazard "fuzz factors"
  4252.     in, either; see question 14.5.)
  4253.  
  4254.     These problems are no worse for C than they are for any other
  4255.     computer language.  Certain aspects of floating-point are
  4256.     usually defined as "however the processor does them" (see also
  4257.     question 11.34), otherwise a compiler for a machine without the
  4258.     "right" model would have to do prohibitively expensive
  4259.     emulations.
  4260.  
  4261.     This article cannot begin to list the pitfalls associated with,
  4262.     and workarounds appropriate for, floating-point work.  A good
  4263.     numerical programming text should cover the basics; see also the
  4264.     references below.
  4265.  
  4266.     References: Kernighan and Plauger, _The Elements of Programming
  4267.     Style_ Sec. 6 pp. 115-8; Knuth, Volume 2 chapter 4; David
  4268.     Goldberg, "What Every Computer Scientist Should Know about
  4269.     Floating-Point Arithmetic".
  4270.  
  4271. 14.5:    What's a good way to check for "close enough" floating-point
  4272.     equality?
  4273.  
  4274. A:    Since the absolute accuracy of floating point values varies, by
  4275.     definition, with their magnitude, the best way of comparing two
  4276.     floating point values is to use an accuracy threshold which is
  4277.     relative to the magnitude of the numbers being compared.  Rather
  4278.     than
  4279.  
  4280.         double a, b;
  4281.         ...
  4282.         if(a == b)    /* WRONG */
  4283.  
  4284.     use something like
  4285.  
  4286.         #include <math.h>
  4287.  
  4288.         if(fabs(a - b) <= epsilon * a)
  4289.  
  4290.     for some suitably-chosen epsilon.
  4291.  
  4292.     References: Knuth Sec. 4.2.2 pp. 217-8.
  4293.  
  4294. 14.6:    How do I round numbers?
  4295.  
  4296. A:    The simplest and most straightforward way is with code like
  4297.  
  4298.         (int)(x + 0.5)
  4299.  
  4300.     This technique won't work properly for negative numbers, though.
  4301.  
  4302. 14.7:    Why doesn't C have an exponentiation operator?
  4303.  
  4304. A:    Because few processors have an exponentiation instruction.  C
  4305.     has a pow() function, declared in <math.h>, although explicit
  4306.     multiplication is often better for small positive integral
  4307.     exponents.
  4308.  
  4309.     References: ANSI Sec. 4.5.5.1; ISO Sec. 7.5.5.1; H&S Sec. 17.6
  4310.     p. 393.
  4311.  
  4312. 14.8:    The pre-#defined constant M_PI seems to be missing from my
  4313.     machine's copy of <math.h>.
  4314.  
  4315. A:    That constant (which is apparently supposed to be the value of
  4316.     pi, accurate to the machine's precision), is not standard.  If
  4317.     you need pi, you'll have to #define it yourself.
  4318.  
  4319.     References: PCS Sec. 13 p. 237.
  4320.  
  4321. 14.9:    How do I test for IEEE NaN and other special values?
  4322.  
  4323. A:    Many systems with high-quality IEEE floating-point
  4324.     implementations provide facilities (e.g. predefined constants,
  4325.     and functions like isnan(), either as nonstandard extensions in
  4326.     <math.h> or perhaps in <ieee.h> or <nan.h>) to deal with these
  4327.     values cleanly, and work is being done to formally standardize
  4328.     such facilities.  A crude but usually effective test for NaN is
  4329.     exemplified by
  4330.  
  4331.         #define isnan(x) ((x) != (x))
  4332.  
  4333.     although non-IEEE-aware compilers may optimize the test away.
  4334.  
  4335.     Another possibility is to to format the value in question using
  4336.     sprintf(): on many systems it generates strings like "NaN" and
  4337.     "Inf" which you could compare for in a pinch.
  4338.  
  4339.     See also question 19.39.
  4340.  
  4341. 14.11:    What's a good way to implement complex numbers in C?
  4342.  
  4343. A:    It is straightforward to define a simple structure and some
  4344.     arithmetic functions to manipulate them.  See also questions
  4345.     2.7, 2.10, and 14.12.
  4346.  
  4347. 14.12:    I'm looking for some code to do:
  4348.         Fast Fourier Transforms (FFT's)
  4349.         matrix arithmetic (multiplication, inversion, etc.)
  4350.         complex arithmetic
  4351.  
  4352. A:    Ajay Shah maintains an index of free numerical software; it is
  4353.     posted periodically, and available where this FAQ list is
  4354.     archived (see question 20.40).  See also question 18.16.
  4355.  
  4356. 14.13:    I'm having trouble with a Turbo C program which crashes and says
  4357.     something like "floating point formats not linked."
  4358.  
  4359. A:    The message in the question has to do with an indecent problem
  4360.     in Borland's compilers, which for some unfathomable reason has
  4361.     still not been fixed.  However, by the newly-passed
  4362.     Communications Decency Act of the U.S., I am prohibited from
  4363.     transmitting or discussing "indecent" material.  (If the fact
  4364.     that users of Borland's compilers are still having this problem
  4365.     isn't indecent, I don't know what is.)  If you send me e-mail
  4366.     certifying that you are over 18 years of age, I may be able to
  4367.     help you.  (You may also be able to see the
  4368.     comp.os.msdos.programmer FAQ list for more information.)
  4369.  
  4370.  
  4371. Section 15. Variable-Length Argument Lists
  4372.  
  4373. 15.1:    I heard that you have to #include <stdio.h> before calling
  4374.     printf().  Why?
  4375.  
  4376. A:    So that a proper prototype for printf() will be in scope.
  4377.  
  4378.     A compiler may use a different calling sequence for functions
  4379.     which accept variable-length argument lists.  (It might do so if
  4380.     calls using variable-length argument lists were less efficient
  4381.     than those using fixed-length.)  Therefore, a prototype
  4382.     (indicating, using the ellipsis notation "...", that the
  4383.     argument list is of variable length) must be in scope whenever a
  4384.     varargs function is called, so that the compiler knows to use
  4385.     the varargs calling mechanism.
  4386.  
  4387.     References: ANSI Sec. 3.3.2.2, Sec. 4.1.6; ISO Sec. 6.3.2.2,
  4388.     Sec. 7.1.7; Rationale Sec. 3.3.2.2, Sec. 4.1.6; H&S Sec. 9.2.4
  4389.     pp. 268-9, Sec. 9.6 pp. 275-6.
  4390.  
  4391. 15.2:    How can %f be used for both float and double arguments in
  4392.     printf()?  Aren't they different types?
  4393.  
  4394. A:    In the variable-length part of a variable-length argument list,
  4395.     the "default argument promotions" apply: types char and
  4396.     short int are promoted to int, and float is promoted to double.
  4397.     (These are the same promotions that apply to function calls
  4398.     without a prototype in scope, also known as "old style" function
  4399.     calls; see question 11.3.)  Therefore, printf's %f format always
  4400.     sees a double.  (Similarly, %c always sees an int, as does %hd.)
  4401.     See also questions 12.9 and 12.13.
  4402.  
  4403.     References: ANSI Sec. 3.3.2.2; ISO Sec. 6.3.2.2; H&S Sec. 6.3.5
  4404.     p. 177, Sec. 9.4 pp. 272-3.
  4405.  
  4406. 15.3:    I had a frustrating problem which turned out to be caused by the
  4407.     line
  4408.  
  4409.         printf("%d", n);
  4410.  
  4411.     where n was actually a long int.  I thought that ANSI function
  4412.     prototypes were supposed to guard against argument type
  4413.     mismatches like this.
  4414.  
  4415. A:    When a function accepts a variable number of arguments, its
  4416.     prototype does not (and cannot) provide any information about
  4417.     the number and types of those variable arguments.  Therefore,
  4418.     the usual protections do *not* apply in the variable-length part
  4419.     of variable-length argument lists: the compiler cannot perform
  4420.     implicit conversions or (in general) warn about mismatches.
  4421.  
  4422.     See also questions 5.2, 11.3, 12.9, and 15.2.
  4423.  
  4424. 15.4:    How can I write a function that takes a variable number of
  4425.     arguments?
  4426.  
  4427. A:    Use the facilities of the <stdarg.h> header.
  4428.  
  4429.     Here is a function which concatenates an arbitrary number of
  4430.     strings into malloc'ed memory:
  4431.  
  4432.         #include <stdlib.h>        /* for malloc, NULL, size_t */
  4433.         #include <stdarg.h>        /* for va_ stuff */
  4434.         #include <string.h>        /* for strcat et al. */
  4435.  
  4436.         char *vstrcat(char *first, ...)
  4437.         {
  4438.             size_t len;
  4439.             char *retbuf;
  4440.             va_list argp;
  4441.             char *p;
  4442.  
  4443.             if(first == NULL)
  4444.                 return NULL;
  4445.  
  4446.             len = strlen(first);
  4447.  
  4448.             va_start(argp, first);
  4449.  
  4450.             while((p = va_arg(argp, char *)) != NULL)
  4451.                 len += strlen(p);
  4452.  
  4453.             va_end(argp);
  4454.  
  4455.             retbuf = malloc(len + 1);    /* +1 for trailing \0 */
  4456.  
  4457.             if(retbuf == NULL)
  4458.                 return NULL;        /* error */
  4459.  
  4460.             (void)strcpy(retbuf, first);
  4461.  
  4462.             va_start(argp, first);        /* restart for second scan */
  4463.  
  4464.             while((p = va_arg(argp, char *)) != NULL)
  4465.                 (void)strcat(retbuf, p);
  4466.  
  4467.             va_end(argp);
  4468.  
  4469.             return retbuf;
  4470.         }
  4471.  
  4472.     Usage is something like
  4473.  
  4474.         char *str = vstrcat("Hello, ", "world!", (char *)NULL);
  4475.  
  4476.     Note the cast on the last argument; see questions 5.2 and 15.3.
  4477.     (Also note that the caller must free the returned, malloc'ed
  4478.     storage.)
  4479.  
  4480.     Under a pre-ANSI compiler, rewrite the function definition
  4481.     without a prototype ("char *vstrcat(first) char *first; {"),
  4482.     include <stdio.h> rather than <stdlib.h>, add "extern
  4483.     char *malloc();", and use int instead of size_t.  You may also
  4484.     have to delete the (void) casts, and use the older varargs
  4485.     package instead of stdarg.  See also question 15.7.
  4486.  
  4487.     References: K&R2 Sec. 7.3 p. 155, Sec. B7 p. 254; ANSI Sec. 4.8;
  4488.     ISO Sec. 7.8; Rationale Sec. 4.8; H&S Sec. 11.4 pp. 296-9; CT&P
  4489.     Sec. A.3 pp. 139-141; PCS Sec. 11 pp. 184-5, Sec. 13 p. 242.
  4490.  
  4491. 15.5:    How can I write a function that takes a format string and a
  4492.     variable number of arguments, like printf(), and passes them to
  4493.     printf() to do most of the work?
  4494.  
  4495. A:    Use vprintf(), vfprintf(), or vsprintf().
  4496.  
  4497.     Here is an error() routine which prints an error message,
  4498.     preceded by the string "error: " and terminated with a newline:
  4499.  
  4500.         #include <stdio.h>
  4501.         #include <stdarg.h>
  4502.  
  4503.         void error(char *fmt, ...)
  4504.         {
  4505.             va_list argp;
  4506.             fprintf(stderr, "error: ");
  4507.             va_start(argp, fmt);
  4508.             vfprintf(stderr, fmt, argp);
  4509.             va_end(argp);
  4510.             fprintf(stderr, "\n");
  4511.         }
  4512.  
  4513.     See also question 15.7.
  4514.  
  4515.     References: K&R2 Sec. 8.3 p. 174, Sec. B1.2 p. 245; ANSI
  4516.     Secs. 4.9.6.7,4.9.6.8,4.9.6.9; ISO
  4517.     Secs. 7.9.6.7,7.9.6.8,7.9.6.9; H&S Sec. 15.12 pp. 379-80; PCS
  4518.     Sec. 11 pp. 186-7.
  4519.  
  4520. 15.6:    How can I write a function analogous to scanf(), that calls
  4521.     scanf() to do most of the work?
  4522.  
  4523. A:    Unfortunately, vscanf and the like are not standard.  You're on
  4524.     your own.
  4525.  
  4526. 15.7:    I have a pre-ANSI compiler, without <stdarg.h>.  What can I do?
  4527.  
  4528. A:    There's an older header, <varargs.h>, which offers about the
  4529.     same functionality.
  4530.  
  4531.     To rewrite the error() function from question 15.5 to use
  4532.     <varargs.h>, change the function header to:
  4533.  
  4534.         void error(va_alist)
  4535.         va_dcl
  4536.         {
  4537.             char *fmt;
  4538.  
  4539.     change the va_start line to
  4540.  
  4541.         va_start(argp);
  4542.  
  4543.     and add the line
  4544.  
  4545.         fmt = va_arg(argp, char *);
  4546.  
  4547.     between the calls to va_start and vfprintf.  (Note that there is
  4548.     no semicolon after va_dcl.)
  4549.  
  4550.     References: H&S Sec. 11.4 pp. 296-9; CT&P Sec. A.2 pp. 134-139;
  4551.     PCS Sec. 11 pp. 184-5, Sec. 13 p. 250.
  4552.  
  4553. 15.8:    How can I discover how many arguments a function was actually
  4554.     called with?
  4555.  
  4556. A:    This information is not available to a portable program.  Some
  4557.     old systems provided a nonstandard nargs() function, but its use
  4558.     was always questionable, since it typically returned the number
  4559.     of words passed, not the number of arguments.  (Structures, long
  4560.     ints, and floating point values are usually passed as several
  4561.     words.)
  4562.  
  4563.     Any function which takes a variable number of arguments must be
  4564.     able to determine *from the arguments themselves* how many of
  4565.     them there are.  printf-like functions do this by looking for
  4566.     formatting specifiers (%d and the like) in the format string
  4567.     (which is why these functions fail badly if the format string
  4568.     does not match the argument list).  Another common technique,
  4569.     applicable when the arguments are all of the same type, is to
  4570.     use a sentinel value (often 0, -1, or an appropriately-cast null
  4571.     pointer) at the end of the list (see the execl() and vstrcat()
  4572.     examples in questions 5.2 and 15.4).  Finally, if their types
  4573.     are predictable, you can pass an explicit count of the number of
  4574.     variable arguments (although it's usually a nuisance for the
  4575.     caller to generate).
  4576.  
  4577.     References: PCS Sec. 11 pp. 167-8.
  4578.  
  4579. 15.9:    My compiler isn't letting me declare a function
  4580.  
  4581.         int f(...)
  4582.         {
  4583.         }
  4584.  
  4585.     i.e. with no fixed arguments.
  4586.  
  4587. A:    Standard C requires at least one fixed argument, in part so that
  4588.     you can hand it to va_start().
  4589.  
  4590.     References: ANSI Sec. 3.5.4, Sec. 3.5.4.3, Sec. 4.8.1.1; ISO
  4591.     Sec. 6.5.4, Sec. 6.5.4.3, Sec. 7.8.1.1; H&S Sec. 9.2 p. 263.
  4592.  
  4593. 15.10:    I have a varargs function which accepts a float parameter.  Why
  4594.     isn't
  4595.  
  4596.         va_arg(argp, float)
  4597.  
  4598.     working?
  4599.  
  4600. A:    In the variable-length part of variable-length argument lists,
  4601.     the old "default argument promotions" apply: arguments of type
  4602.     float are always promoted (widened) to type double, and types
  4603.     char and short int are promoted to int.  Therefore, it is never
  4604.     correct to invoke va_arg(argp, float); instead you should always
  4605.     use va_arg(argp, double).  Similarly, use va_arg(argp, int) to
  4606.     retrieve arguments which were originally char, short, or int.
  4607.     See also questions 11.3 and 15.2.
  4608.  
  4609.     References: ANSI Sec. 3.3.2.2; ISO Sec. 6.3.2.2; Rationale
  4610.     Sec. 4.8.1.2; H&S Sec. 11.4 p. 297.
  4611.  
  4612. 15.11:    I can't get va_arg() to pull in an argument of type pointer-to-
  4613.     function.
  4614.  
  4615. A:    The type-rewriting games which the va_arg() macro typically
  4616.     plays are stymied by overly-complicated types such as pointer-to-
  4617.     function.  If you use a typedef for the function pointer type,
  4618.     however, all will be well.  See also question 1.21.
  4619.  
  4620.     References: ANSI Sec. 4.8.1.2; ISO Sec. 7.8.1.2; Rationale
  4621.     Sec. 4.8.1.2.
  4622.  
  4623. 15.12:    How can I write a function which takes a variable number of
  4624.     arguments and passes them to some other function (which takes a
  4625.     variable number of arguments)?
  4626.  
  4627. A:    In general, you cannot.  Ideally, you should provide a version
  4628.     of that other function which accepts a va_list pointer
  4629.     (analogous to vfprintf(); see question 15.5 above).  If the
  4630.     arguments must be passed directly as actual arguments, or if you
  4631.     do not have the option of rewriting the second function to
  4632.     accept a va_list (in other words, if the second, called function
  4633.     must accept a variable number of arguments, not a va_list), no
  4634.     portable solution is possible.  (The problem could perhaps be
  4635.     solved by resorting to machine-specific assembly language; see
  4636.     also question 15.13 below.)
  4637.  
  4638. 15.13:    How can I call a function with an argument list built up at run
  4639.     time?
  4640.  
  4641. A:    There is no guaranteed or portable way to do this.  If you're
  4642.     curious, ask this list's editor, who has a few wacky ideas you
  4643.     could try...
  4644.  
  4645.     Instead of an actual argument list, you might consider passing
  4646.     an array of generic (void *) pointers.  The called function can
  4647.     then step through the array, much like main() might step through
  4648.     argv.  (Obviously this works only if you have control over all
  4649.     the called functions.)
  4650.  
  4651.     (See also question 19.36.)
  4652.  
  4653.  
  4654. Section 16. Strange Problems
  4655.  
  4656. 16.3:    This program crashes before it even runs!  (When single-stepping
  4657.     with a debugger, it dies before the first statement in main().)
  4658.  
  4659. A:    You probably have one or more very large (kilobyte or more)
  4660.     local arrays.  Many systems have fixed-size stacks, and those
  4661.     which perform dynamic stack allocation automatically (e.g. Unix)
  4662.     can be confused when the stack tries to grow by a huge chunk all
  4663.     at once.  It is often better to declare large arrays with static
  4664.     duration (unless of course you need a fresh set with each
  4665.     recursive call, in which case you could dynamically allocate
  4666.     them with malloc(); see also question 1.31).
  4667.  
  4668.     (See also questions 11.12, 16.4, 16.5, and 18.4.)
  4669.  
  4670. 16.4:    I have a program that seems to run correctly, but it crashes as
  4671.     it's exiting, *after* the last statement in main().  What could
  4672.     be causing this?
  4673.  
  4674. A:    Look for a misdeclared main() (see questions 2.18 and 10.9), or
  4675.     local buffers passed to setbuf() or setvbuf(), or problems in
  4676.     cleanup functions registered by atexit().  See also questions
  4677.     7.5 and 11.16.
  4678.  
  4679.     References: CT&P Sec. 5.3 pp. 72-3.
  4680.  
  4681. 16.5:    This program runs perfectly on one machine, but I get weird
  4682.     results on another.  Stranger still, adding or removing
  4683.     debugging printouts changes the symptoms...
  4684.  
  4685. A:    Lots of things could be going wrong; here are a few of the more
  4686.     common things to check:
  4687.  
  4688.         uninitialized local variables (see also question 7.1)
  4689.  
  4690.         integer overflow, especially on 16-bit machines,
  4691.         especially of an intermediate result when doing things
  4692.         like a * b / c (see also question 3.14)
  4693.  
  4694.         undefined evaluation order (see questions 3.1 through 3.4)
  4695.  
  4696.         omitted declaration of external functions, especially
  4697.         those which return something other than int
  4698.         (see questions 1.25 and 14.2)
  4699.  
  4700.         dereferenced null pointers (see section 5)
  4701.  
  4702.         improper malloc/free use: assuming malloc'ed memory
  4703.         contains 0, assuming freed storage persists, freeing
  4704.         something twice (see also questions 7.20 and 7.19)
  4705.  
  4706.         pointer problems in general (see also question 16.8)
  4707.  
  4708.         mismatch between printf() format and arguments, especially
  4709.         trying to print long ints using %d (see question 12.9)
  4710.  
  4711.         trying to malloc(256 * 256 * sizeof(double)), especially
  4712.         on machines with limited memory (see also questions 7.16
  4713.         and 19.23)
  4714.  
  4715.         array bounds problems, especially of small, temporary
  4716.         buffers, perhaps used for constructing strings with
  4717.         sprintf() (see also questions 7.1 and 12.21)
  4718.  
  4719.         invalid assumptions about the mapping of typedefs,
  4720.         especially size_t
  4721.  
  4722.         floating point problems (see questions 14.1 and 14.4)
  4723.  
  4724.         anything you thought was a clever exploitation of the way
  4725.         you believe code is generated for your specific system
  4726.  
  4727.     Proper use of function prototypes can catch several of these
  4728.     problems; lint would catch several more.  See also questions
  4729.     16.3, 16.4, and 18.4.
  4730.  
  4731. 16.6:    Why does this code:
  4732.  
  4733.         char *p = "hello, world!";
  4734.         p[0] = 'H';
  4735.  
  4736.     crash?
  4737.  
  4738. A:    String literals are not necessarily modifiable, except (in
  4739.     effect) when they are used as array initializers.  Try
  4740.  
  4741.         char a[] = "hello, world!";
  4742.  
  4743.     See also question 1.32.
  4744.  
  4745.     References: ANSI Sec. 3.1.4; ISO Sec. 6.1.4; H&S Sec. 2.7.4 pp.
  4746.     31-2.
  4747.  
  4748. 16.8:    What do "Segmentation violation" and "Bus error" mean?
  4749.  
  4750. A:    These generally mean that your program tried to access memory it
  4751.     shouldn't have, invariably as a result of improper pointer use.
  4752.     Likely causes are inadvertent use of null pointers (see also
  4753.     questions 5.2 and 5.20) or uninitialized, misaligned, or
  4754.     otherwise improperly allocated pointers (see questions 7.1 and
  4755.     7.2); corruption of the malloc arena (see question 7.19); and
  4756.     mismatched function arguments, especially involving pointers;
  4757.     two possibilities are scanf() (see question 12.12) and fprintf()
  4758.     (make sure it receives its first FILE * argument).
  4759.  
  4760.     See also questions 16.3 and 16.4.
  4761.  
  4762.  
  4763. Section 17. Style
  4764.  
  4765. 17.1:    What's the best style for code layout in C?
  4766.  
  4767. A:    K&R, while providing the example most often copied, also supply
  4768.     a good excuse for disregarding it:
  4769.  
  4770.         The position of braces is less important,
  4771.         although people hold passionate beliefs.
  4772.         We have chosen one of several popular styles.
  4773.         Pick a style that suits you, then use it
  4774.         consistently.
  4775.  
  4776.     It is more important that the layout chosen be consistent (with
  4777.     itself, and with nearby or common code) than that it be
  4778.     "perfect."  If your coding environment (i.e. local custom or
  4779.     company policy) does not suggest a style, and you don't feel
  4780.     like inventing your own, just copy K&R.  (The tradeoffs between
  4781.     various indenting and brace placement options can be
  4782.     exhaustively and minutely examined, but don't warrant repetition
  4783.     here.  See also the Indian Hill Style Guide.)
  4784.  
  4785.     The elusive quality of "good style" involves much more than mere
  4786.     code layout details; don't spend time on formatting to the
  4787.     exclusion of more substantive code quality issues.
  4788.  
  4789.     See also question 10.6.
  4790.  
  4791.     References: K&R1 Sec. 1.2 p. 10; K&R2 Sec. 1.2 p. 10.
  4792.  
  4793. 17.3:    Here's a neat trick for checking whether two strings are equal:
  4794.  
  4795.         if(!strcmp(s1, s2))
  4796.  
  4797.     Is this good style?
  4798.  
  4799. A:    It is not particularly good style, although it is a popular
  4800.     idiom.  The test succeeds if the two strings are equal, but the
  4801.     use of ! ("not") suggests that it tests for inequality.
  4802.  
  4803.     A better option is to use a macro:
  4804.  
  4805.         #define Streq(s1, s2) (strcmp((s1), (s2)) == 0)
  4806.  
  4807.     Opinions on code style, like those on religion, can be debated
  4808.     endlessly.  Though good style is a worthy goal, and can usually
  4809.     be recognized, it cannot be rigorously codified.  See also
  4810.     question 17.10.
  4811.  
  4812. 17.4:    Why do some people write if(0 == x) instead of if(x == 0)?
  4813.  
  4814. A:    It's a trick to guard against the common error of writing
  4815.  
  4816.         if(x = 0)
  4817.  
  4818.     If you're in the habit of writing the constant before the ==,
  4819.     the compiler will complain if you accidentally type
  4820.  
  4821.         if(0 = x)
  4822.  
  4823.     Evidently it can be easier to remember to reverse the test than
  4824.     it is to remember to type the doubled = sign.
  4825.  
  4826.     References: H&S Sec. 7.6.5 pp. 209-10.
  4827.  
  4828. 17.5:    I came across some code that puts a (void) cast before each call
  4829.     to printf().  Why?
  4830.  
  4831. A:    printf() does return a value, though few programs bother to
  4832.     check the return values from each call.  Since some compilers
  4833.     (and lint) will warn about discarded return values, an explicit
  4834.     cast to (void) is a way of saying "Yes, I've decided to ignore
  4835.     the return value from this call, but please continue to warn me
  4836.     about other (perhaps inadvertently) ignored return values."
  4837.     It's also common to use void casts on calls to strcpy() and
  4838.     strcat(), since the return value is never surprising.
  4839.  
  4840.     References: K&R2 Sec. A6.7 p. 199; Rationale Sec. 3.3.4; H&S
  4841.     Sec. 6.2.9 p. 172, Sec. 7.13 pp. 229-30.
  4842.  
  4843. 17.8:    What is "Hungarian Notation"?  Is it worthwhile?
  4844.  
  4845. A:    Hungarian Notation is a naming convention, invented by Charles
  4846.     Simonyi, which encodes things about a variable's type (and
  4847.     perhaps its intended use) in its name.  It is well-loved in some
  4848.     circles and roundly castigated in others.  Its chief advantage
  4849.     is that it makes a variable's type or intended use obvious from
  4850.     its name; its chief disadvantage is that type information is not
  4851.     necessarily a worthwhile thing to carry around in the name of a
  4852.     variable.
  4853.  
  4854.     References: Simonyi and Heller, "The Hungarian Revolution" .
  4855.  
  4856. 17.9:    Where can I get the "Indian Hill Style Guide" and other coding
  4857.     standards?
  4858.  
  4859. A:    Various documents are available for anonymous ftp from:
  4860.  
  4861.         Site:            File or directory:
  4862.  
  4863.         cs.washington.edu    pub/cstyle.tar.Z
  4864.                     (the updated Indian Hill guide)
  4865.  
  4866.         ftp.cs.toronto.edu    doc/programming
  4867.                     (including Henry Spencer's
  4868.                     "10 Commandments for C Programmers")
  4869.  
  4870.         ftp.cs.umd.edu        pub/style-guide
  4871.  
  4872.     You may also be interested in the books _The Elements of
  4873.     Programming Style_, _Plum Hall Programming Guidelines_, and _C
  4874.     Style: Standards and Guidelines_; see the Bibliography.  (The
  4875.     _Standards and Guidelines_ book is not in fact a style guide,
  4876.     but a set of guidelines on selecting and creating style guides.)
  4877.  
  4878.     See also question 18.9.
  4879.  
  4880. 17.10:    Some people say that goto's are evil and that I should never use
  4881.     them.  Isn't that a bit extreme?
  4882.  
  4883. A:    Programming style, like writing style, is somewhat of an art and
  4884.     cannot be codified by inflexible rules, although discussions
  4885.     about style often seem to center exclusively around such rules.
  4886.  
  4887.     In the case of the goto statement, it has long been observed
  4888.     that unfettered use of goto's quickly leads to unmaintainable
  4889.     spaghetti code.  However, a simple, unthinking ban on the goto
  4890.     statement does not necessarily lead immediately to beautiful
  4891.     programming: an unstructured programmer is just as capable of
  4892.     constructing a Byzantine tangle without using any goto's
  4893.     (perhaps substituting oddly-nested loops and Boolean control
  4894.     variables, instead).
  4895.  
  4896.     Most observations or "rules" about programming style usually
  4897.     work better as guidelines than rules, and work much better if
  4898.     programmers understand what the guidelines are trying to
  4899.     accomplish.  Blindly avoiding certain constructs or following
  4900.     rules without understanding them can lead to just as many
  4901.     problems as the rules were supposed to avert.
  4902.  
  4903.     Furthermore, many opinions on programming style are just that:
  4904.     opinions.  It's usually futile to get dragged into "style wars,"
  4905.     because on certain issues (such as those referred to in
  4906.     questions 9.2, 5.3, 5.9, and 10.7), opponents can never seem to
  4907.     agree, or agree to disagree, or stop arguing.
  4908.  
  4909.  
  4910. Section 18. Tools and Resources
  4911.  
  4912. 18.1:    I need:                 A:    Look for programs (see also
  4913.                     question 18.16) named:
  4914.  
  4915.     a C cross-reference        cflow, cxref, calls, cscope,
  4916.     generator            xscope, or ixfw
  4917.  
  4918.     a C beautifier/pretty-        cb, indent, GNU indent, or
  4919.     printer                vgrind
  4920.  
  4921.     a revision control or        RCS or SCCS
  4922.     configuration management
  4923.     tool
  4924.  
  4925.     a C source obfuscator        obfus, shroud, or opqcp
  4926.     (shrouder)
  4927.  
  4928.     a "make" dependency        makedepend, or try cc -M or
  4929.     generator            cpp -M
  4930.  
  4931.     tools to compute code        ccount, Metre, lcount, or
  4932.     metrics                csize, or see URL
  4933.                     http://www.qucis.queensu.ca:1999/Software-
  4934.                     Engineering/Cmetrics.html ;
  4935.                     there is also a package sold
  4936.                     by McCabe and Associates
  4937.  
  4938.     a C lines-of-source        this can be done very
  4939.     counter                crudely with the standard
  4940.                     Unix utility wc, and
  4941.                     considerably better with
  4942.                     grep -c ";"
  4943.  
  4944.     a prototype generator        see question 11.31
  4945.  
  4946.     a tool to track down
  4947.     malloc problems            see question 18.2
  4948.  
  4949.     a "selective" C
  4950.     preprocessor            see question 10.18
  4951.  
  4952.     language translation        see questions 11.31 and
  4953.     tools                 20.26
  4954.  
  4955.     C verifiers (lint)        see question 18.7
  4956.  
  4957.     a C compiler!            see question 18.3
  4958.  
  4959.     (This list of tools is by no means complete; if you know of tools
  4960.     not mentioned, you're welcome to contact this list's maintainer.)
  4961.  
  4962.     Other lists of tools, and discussion about them, can be found in
  4963.     the Usenet newsgroups comp.compilers and comp.software-eng .
  4964.  
  4965.     See also questions 18.16 and 18.3.
  4966.  
  4967. 18.2:    How can I track down these pesky malloc problems?
  4968.  
  4969. A:    A number of debugging packages exist to help track down malloc
  4970.     problems; one popular one is Conor P. Cahill's "dbmalloc,"
  4971.     posted to comp.sources.misc in 1992, volume 32.  Others are
  4972.     "leak," available in volume 27 of the comp.sources.unix
  4973.     archives; JMalloc.c and JMalloc.h in the "Snippets" collection;
  4974.     and MEMDEBUG from ftp.crpht.lu in pub/sources/memdebug .  See
  4975.     also question 18.16.
  4976.  
  4977.     A number of commercial debugging tools exist, and can be
  4978.     invaluable in tracking down malloc-related and other stubborn
  4979.     problems:
  4980.  
  4981.         Bounds-Checker for DOS, from Nu-Mega Technologies,
  4982.         P.O. Box 7780, Nashua, NH 03060-7780, USA, 603-889-2386.
  4983.  
  4984.         CodeCenter (formerly Saber-C) from Centerline Software
  4985.         (formerly Saber), 10 Fawcett Street, Cambridge, MA
  4986.         02138-1110, USA, 617-498-3000.
  4987.  
  4988.         Insight, from ParaSoft Corporation, 2500 E. Foothill
  4989.         Blvd., Pasadena, CA 91107, USA, 818-792-9941,
  4990.         insight@parasoft.com .
  4991.  
  4992.         Purify, from Pure Software, 1309 S. Mary Ave., Sunnyvale,
  4993.         CA 94087, USA, 800-224-7873, info-home@pure.com .
  4994.  
  4995.         Sentinel, from AIB Software, 1145 Herndon Pkwy #200, Herndon,
  4996.         VA 22070, USA, 703-787-7700, 800-296-3000, info@aib.com .
  4997.  
  4998. 18.3:    What's a free or cheap C compiler I can use?
  4999.  
  5000. A:    A popular and high-quality free C compiler is the FSF's GNU C
  5001.     compiler, or gcc.  It is available by anonymous ftp from
  5002.     prep.ai.mit.edu in directory pub/gnu, or at several other FSF
  5003.     archive sites.  An MS-DOS port, djgpp, is also available; it can
  5004.     be found in the Simtel and Oakland archives and probably many
  5005.     others, usually in a directory like pub/msdos/djgpp/ or
  5006.     simtel/msdos/djgpp/.
  5007.  
  5008.     There is a shareware compiler called PCC, available as
  5009.     PCC12C.ZIP .
  5010.  
  5011.     A very inexpensive MS-DOS compiler is Power C from Mix Software,
  5012.     1132 Commerce Drive, Richardson, TX 75801, USA, 214-783-6001.
  5013.  
  5014.     Another recently-developed compiler is lcc, available for
  5015.     anonymous ftp from ftp.cs.princeton.edu in pub/lcc.
  5016.  
  5017.     Archives associated with comp.compilers contain a great deal of
  5018.     information about available compilers, interpreters, grammars,
  5019.     etc. (for many languages).  The comp.compilers archives
  5020.     (including an FAQ list), maintained by the moderator, John R.
  5021.     Levine, are at iecc.com .  A list of available compilers and
  5022.     related resources, maintained by Mark Hopkins, Steven Robenalt,
  5023.     and David Muir Sharnoff, is at ftp.idiom.com in pub/compilers-
  5024.     list/.  (See also the comp.compilers directory in the
  5025.     news.answers archives at rtfm.mit.edu and ftp.uu.net; see
  5026.     question 20.40.)
  5027.  
  5028.     See also question 18.16.
  5029.  
  5030. 18.4:    I just typed in this program, and it's acting strangely.  Can
  5031.     you see anything wrong with it?
  5032.  
  5033. A:    See if you can run lint first (perhaps with the -a, -c, -h, -p
  5034.     or other options).  Many C compilers are really only half-
  5035.     compilers, electing not to diagnose numerous source code
  5036.     difficulties which would not actively preclude code generation.
  5037.  
  5038.     See also questions 16.5 and 16.8.
  5039.  
  5040.     References: Ian Darwin, _Checking C Programs with lint_ .
  5041.  
  5042. 18.5:    How can I shut off the "warning: possible pointer alignment
  5043.     problem" message which lint gives me for each call to malloc()?
  5044.  
  5045. A:    The problem is that traditional versions of lint do not know,
  5046.     and cannot be told, that malloc() "returns a pointer to space
  5047.     suitably aligned for storage of any type of object."  It is
  5048.     possible to provide a pseudoimplementation of malloc(), using a
  5049.     #define inside of #ifdef lint, which effectively shuts this
  5050.     warning off, but a simpleminded definition will also suppress
  5051.     meaningful messages about truly incorrect invocations.  It may
  5052.     be easier simply to ignore the message, perhaps in an automated
  5053.     way with grep -v.  (But don't get in the habit of ignoring too
  5054.     many lint messages, otherwise one day you'll overlook a
  5055.     significant one.)
  5056.  
  5057. 18.7:    Where can I get an ANSI-compatible lint?
  5058.  
  5059. A:    Products called PC-Lint and FlexeLint (in "shrouded source
  5060.     form," for compilation on 'most any system) are available from
  5061.  
  5062.         Gimpel Software
  5063.         3207 Hogarth Lane
  5064.         Collegeville, PA  19426  USA
  5065.         (+1) 610 584 4261
  5066.         gimpel@netaxs.com
  5067.  
  5068.     The Unix System V release 4 lint is ANSI-compatible, and is
  5069.     available separately (bundled with other C tools) from UNIX
  5070.     Support Labs or from System V resellers.
  5071.  
  5072.     Another ANSI-compatible lint (which can also perform higher-
  5073.     level formal verification) is LCLint, available via anonymous
  5074.     ftp from larch.lcs.mit.edu in pub/Larch/lclint/.
  5075.  
  5076.     In the absence of lint, many modern compilers do attempt to
  5077.     diagnose almost as many problems as lint does.
  5078.  
  5079. 18.8:    Don't ANSI function prototypes render lint obsolete?
  5080.  
  5081. A:    Not really.  First of all, prototypes work only if they are
  5082.     present and correct; an inadvertently incorrect prototype is
  5083.     worse than useless.  Secondly, lint checks consistency across
  5084.     multiple source files, and checks data declarations as well as
  5085.     functions.  Finally, an independent program like lint will
  5086.     probably always be more scrupulous at enforcing compatible,
  5087.     portable coding practices than will any particular,
  5088.     implementation-specific, feature- and extension-laden compiler.
  5089.  
  5090.     If you do want to use function prototypes instead of lint for
  5091.     cross-file consistency checking, make sure that you set the
  5092.     prototypes up correctly in header files.  See questions 1.7 and
  5093.     10.6.
  5094.  
  5095. 18.9:    Are there any C tutorials or other resources on the net?
  5096.  
  5097. A:    There are several of them:
  5098.  
  5099.     "Notes for C programmers," by Christopher Sawtell, are
  5100.     available from svr-ftp.eng.cam.ac.uk in misc/sawtell_C.shar and
  5101.     garbo.uwasa.fi in /pc/c-lang/c-lesson.zip .
  5102.  
  5103.     Tim Love's "C for Programmers" is available by ftp from svr-
  5104.     ftp.eng.cam.ac.uk in the misc directory.  An html version is at
  5105.     http://club.eng.cam.ac.uk/help/tpl/languages/C/teaching_C/teaching_C.html .
  5106.  
  5107.     The Coronado Enterprises C tutorials are available on Simtel
  5108.     mirrors in pub/msdos/c/.
  5109.  
  5110.     Rick Rowe has a tutorial which is available from ftp.netcom.com
  5111.     as pub/rowe/tutorde.zip or ftp.wustl.edu as
  5112.     pub/MSDOS_UPLOADS/programming/c_language/ctutorde.zip .
  5113.  
  5114.     There is evidently a web-based course at
  5115.     http://www.strath.ac.uk/CC/Courses/CCourse/CCourse.html .
  5116.  
  5117.     Finally, on some Unix machines you can try typing learn c at the
  5118.     shell prompt.
  5119.  
  5120.     [Disclaimer: I have not reviewed these tutorials; I have heard
  5121.     that at least one of them contains a number of errors.  Also,
  5122.     this sort of information rapidly becomes out-of-date; these
  5123.     addresses may not work by the time you read this and try them.]
  5124.  
  5125.     Several of these tutorials, plus a great deal of other
  5126.     information about C, are accessible via the web at
  5127.     http://www.lysator.liu.se/c/index.html .
  5128.  
  5129.     Vinit Carpenter maintains a list of resources for learning C and
  5130.     C++; it is posted to comp.lang.c and comp.lang.c++, and archived
  5131.     where this FAQ list is (see question 20.40), or on the web at
  5132.     http://vinny.csd.mu.edu/ .
  5133.  
  5134.     See also question 18.10 below.
  5135.  
  5136. 18.10:    What's a good book for learning C?
  5137.  
  5138. A:    There are far too many books on C to list here; it's impossible
  5139.     to rate them all.  Many people believe that the best one was
  5140.     also the first: _The C Programming Language_, by Kernighan and
  5141.     Ritchie ("K&R," now in its second edition).  Opinions vary on
  5142.     K&R's suitability as an initial programming text: many of us did
  5143.     learn C from it, and learned it well; some, however, feel that
  5144.     it is a bit too clinical as a first tutorial for those without
  5145.     much programming background.
  5146.  
  5147.     An excellent reference manual is _C: A Reference Manual_, by
  5148.     Samuel P. Harbison and Guy L. Steele, now in its fourth edition.
  5149.  
  5150.     Though not suitable for learning C from scratch, this FAQ list
  5151.     has been published in book form; see the Bibliography.
  5152.  
  5153.     Mitch Wright maintains an annotated bibliography of C and Unix
  5154.     books; it is available for anonymous ftp from ftp.rahul.net in
  5155.     directory pub/mitch/YABL/.
  5156.  
  5157.     This FAQ list's editor maintains a collection of previous
  5158.     answers to this question, which is available upon request.  See
  5159.     also question 18.9 above.
  5160.  
  5161. 18.13:    Where can I find the sources of the standard C libraries?
  5162.  
  5163. A:    One source (though not public domain) is _The Standard C
  5164.     Library_, by P.J. Plauger (see the Bibliography).
  5165.     Implementations of all or part of the C library have been
  5166.     written and are readily available as part of the netBSD and GNU
  5167.     (also Linux) projects.  See also question 18.16.
  5168.  
  5169. 18.14:    I need code to parse and evaluate expressions.
  5170.  
  5171. A:    Two available packages are "defunc," posted to comp.sources.misc
  5172.     in December, 1993 (V41 i32,33), to alt.sources in January, 1994,
  5173.     and available from sunsite.unc.edu in
  5174.     pub/packages/development/libraries/defunc-1.3.tar.Z, and
  5175.     "parse," at lamont.ldgo.columbia.edu.  Other options include the
  5176.     S-Lang interpreter, available via anonymous ftp from
  5177.     amy.tch.harvard.edu in pub/slang, and the shareware Cmm ("C-
  5178.     minus-minus" or "C minus the hard stuff").  See also question
  5179.     18.16.
  5180.  
  5181.     There is also some parsing/evaluation code in _Software
  5182.     Solutions in C_ (chapter 12, pp. 235-55).
  5183.  
  5184. 18.15:    Where can I get a BNF or YACC grammar for C?
  5185.  
  5186. A:    The definitive grammar is of course the one in the ANSI
  5187.     standard; see question 11.2.  Another grammar (along with one
  5188.     for C++) by Jim Roskind is in pub/c++grammar1.1.tar.Z at
  5189.     ics.uci.edu .  A fleshed-out, working instance of the ANSI
  5190.     grammar (due to Jeff Lee) is on ftp.uu.net (see question 18.16)
  5191.     in usenet/net.sources/ansi.c.grammar.Z (including a companion
  5192.     lexer).  The FSF's GNU C compiler contains a grammar, as does
  5193.     the appendix to K&R2.
  5194.  
  5195.     The comp.compilers archives contain more information about
  5196.     grammars; see question 18.3.
  5197.  
  5198.     References: K&R1 Sec. A18 pp. 214-219; K&R2 Sec. A13 pp. 234-
  5199.     239; ANSI Sec. A.2; ISO Sec. B.2; H&S pp. 423-435 Appendix B.
  5200.  
  5201. 18.15a: Does anyone have a C compiler test suite I can use?
  5202.  
  5203. A:    Plum Hall (formerly in Cardiff, NJ; now in Hawaii) sells one;
  5204.     other packages are Ronald Guilmette's RoadTest(tm) Compiler Test
  5205.     Suites (ftp to netcom.com, pub/rfg/roadtest/announce.txt for
  5206.     information) and Nullstone's Automated Compiler Performance
  5207.     Analysis Tool (see http://www.nullstone.com).  The FSF's GNU C
  5208.     (gcc) distribution includes a c-torture-test which checks a
  5209.     number of common problems with compilers.  Kahan's paranoia
  5210.     test, found in netlib/paranoia on netlib.att.com, strenuously
  5211.     tests a C implementation's floating point capabilities.
  5212.  
  5213. 18.16:    Where and how can I get copies of all these freely distributable
  5214.     programs?
  5215.  
  5216. A:    As the number of available programs, the number of publicly
  5217.     accessible archive sites, and the number of people trying to
  5218.     access them all grow, this question becomes both easier and more
  5219.     difficult to answer.
  5220.  
  5221.     There are a number of large, public-spirited archive sites out
  5222.     there, such as ftp.uu.net, archive.umich.edu, oak.oakland.edu,
  5223.     sumex-aim.stanford.edu, and wuarchive.wustl.edu, which have huge
  5224.     amounts of software and other information all freely available.
  5225.     For the FSF's GNU project, the central distribution site is
  5226.     prep.ai.mit.edu .  These well-known sites tend to be extremely
  5227.     busy and hard to reach, but there are also numerous "mirror"
  5228.     sites which try to spread the load around.
  5229.  
  5230.     On the connected Internet, the traditional way to retrieve files
  5231.     from an archive site is with anonymous ftp.  For those without
  5232.     ftp access, there are also several ftp-by-mail servers in
  5233.     operation.  More and more, the world-wide web (WWW) is being
  5234.     used to announce, index, and even transfer large data files.
  5235.     There are probably yet newer access methods, too.
  5236.  
  5237.     Those are some of the easy parts of the question to answer.  The
  5238.     hard part is in the details -- this article cannot begin to
  5239.     track or list all of the available archive sites or all of the
  5240.     various ways of accessing them.  If you have access to the net
  5241.     at all, you probably have access to more up-to-date information
  5242.     about active sites and useful access methods than this FAQ list
  5243.     does.
  5244.  
  5245.     The other easy-and-hard aspect of the question, of course, is
  5246.     simply *finding* which site has what you're looking for.  There
  5247.     is a tremendous amount of work going on in this area, and there
  5248.     are probably new indexing services springing up every day.  One
  5249.     of the first was "archie": for any program or resource available
  5250.     on the net, if you know its name, an archie server can usually
  5251.     tell you which anonymous ftp sites have it.  Your system may
  5252.     have an archie command, or you can send the mail message "help"
  5253.     to archie@archie.cs.mcgill.ca for information.
  5254.  
  5255.     If you have access to Usenet, see the regular postings in the
  5256.     comp.sources.unix and comp.sources.misc newsgroups, which
  5257.     describe the archiving policies for those groups and how to
  5258.     access their archives.  The comp.archives newsgroup contains
  5259.     numerous announcements of anonymous ftp availability of various
  5260.     items.  Finally, the newsgroup comp.sources.wanted is generally
  5261.     a more appropriate place to post queries for source
  5262.     availability, but check *its* FAQ list, "How to find sources,"
  5263.     before posting there.
  5264.  
  5265.     See also question 14.12.
  5266.  
  5267. Section 19. System Dependencies
  5268.  
  5269. 19.1:    How can I read a single character from the keyboard without
  5270.     waiting for the RETURN key?  How can I stop characters from
  5271.     being echoed on the screen as they're typed?
  5272.  
  5273. A:    Alas, there is no standard or portable way to do these things in
  5274.     C.  Concepts such as screens and keyboards are not even
  5275.     mentioned in the Standard, which deals only with simple I/O
  5276.     "streams" of characters.
  5277.  
  5278.     At some level, interactive keyboard input is usually collected
  5279.     and presented to the requesting program a line at a time.  This
  5280.     gives the operating system a chance to support input line
  5281.     editing (backspace/delete/rubout, etc.) in a consistent way,
  5282.     without requiring that it be built into every program.  Only
  5283.     when the user is satisfied and presses the RETURN key (or
  5284.     equivalent) is the line made available to the calling program.
  5285.     Even if the calling program appears to be reading input a
  5286.     character at a time (with getchar() or the like), the first call
  5287.     blocks until the user has typed an entire line, at which point
  5288.     potentially many characters become available and many character
  5289.     requests (e.g. getchar() calls) are satisfied in quick
  5290.     succession.
  5291.  
  5292.     When a program wants to read each character immediately as it
  5293.     arrives, its course of action will depend on where in the input
  5294.     stream the line collection is happening and how it can be
  5295.     disabled.  Under some systems (e.g. MS-DOS, VMS in some modes),
  5296.     a program can use a different or modified set of OS-level input
  5297.     calls to bypass line-at-a-time input processing.  Under other
  5298.     systems (e.g. Unix, VMS in other modes), the part of the
  5299.     operating system responsible for serial input (often called the
  5300.     "terminal driver") must be placed in a mode which turns off line-
  5301.     at-a-time processing, after which all calls to the usual input
  5302.     routines (e.g. read(), getchar(), etc.) will return characters
  5303.     immediately.  Finally, a few systems (particularly older, batch-
  5304.     oriented mainframes) perform input processing in peripheral
  5305.     processors which cannot be told to do anything other than line-
  5306.     at-a-time input.
  5307.  
  5308.     Therefore, when you need to do character-at-a-time input (or
  5309.     disable keyboard echo, which is an analogous problem), you will
  5310.     have to use a technique specific to the system you're using,
  5311.     assuming it provides one.  Since comp.lang.c is oriented towards
  5312.     topics that C does deal with, you will usually get better
  5313.     answers to these questions by referring to a system-specific
  5314.     newsgroup such as comp.unix.questions or
  5315.     comp.os.msdos.programmer, and to the FAQ lists for these groups.
  5316.     Note that the answers are often not unique even across different
  5317.     variants of a system; bear in mind when answering system-
  5318.     specific questions that the answer that applies to your system
  5319.     may not apply to everyone else's.
  5320.  
  5321.     However, since these questions are frequently asked here, here
  5322.     are brief answers for some common situations.
  5323.  
  5324.     Some versions of curses have functions called cbreak(),
  5325.     noecho(), and getch() which do what you want.  If you're
  5326.     specifically trying to read a short password without echo, you
  5327.     might try getpass().  Under Unix, you can use ioctl() to play
  5328.     with the terminal driver modes (CBREAK or RAW under "classic"
  5329.     versions; ICANON, c_cc[VMIN] and c_cc[VTIME] under System V or
  5330.     POSIX systems; ECHO under all versions), or in a pinch, system()
  5331.     and the stty command.  (For more information, see <sgtty.h> and
  5332.     tty(4) under classic versions, <termio.h> and termio(4) under
  5333.     System V, or <termios.h> and termios(4) under POSIX.)  Under MS-
  5334.     DOS, use getch() or getche(), or the corresponding BIOS
  5335.     interrupts.  Under VMS, try the Screen Management (SMG$)
  5336.     routines, or curses, or issue low-level $QIO's with the
  5337.     IO$_READVBLK function code (and perhaps IO$M_NOECHO, and others)
  5338.     to ask for one character at a time.  (It's also possible to set
  5339.     character-at-a-time or "pass through" modes in the VMS terminal
  5340.     driver.)  Under other operating systems, you're on your own.
  5341.  
  5342.     (As an aside, note that simply using setbuf() or setvbuf() to
  5343.     set stdin to unbuffered will *not* generally serve to allow
  5344.     character-at-a-time input.)
  5345.  
  5346.     If you're trying to write a portable program, a good approach is
  5347.     to define your own suite of three functions to (1) set the
  5348.     terminal driver or input system into character-at-a-time mode
  5349.     (if necessary), (2) get characters, and (3) return the terminal
  5350.     driver to its initial state when the program is finished.
  5351.     (Ideally, such a set of functions might be part of the C
  5352.     Standard, some day.)  The extended versions of this FAQ list
  5353.     (see question 20.40) contain examples of such functions for
  5354.     several popular systems.
  5355.  
  5356.     See also question 19.2.
  5357.  
  5358.     References: PCS Sec. 10 pp. 128-9, Sec. 10.1 pp. 130-1; POSIX
  5359.     Sec. 7.
  5360.  
  5361. 19.2:    How can I find out if there are characters available for reading
  5362.     (and if so, how many)?  Alternatively, how can I do a read that
  5363.     will not block if there are no characters available?
  5364.  
  5365. A:    These, too, are entirely operating-system-specific.  Some
  5366.     versions of curses have a nodelay() function.  Depending on your
  5367.     system, you may also be able to use "nonblocking I/O", or a
  5368.     system call named "select" or "poll", or the FIONREAD ioctl, or
  5369.     c_cc[VTIME], or kbhit(), or rdchk(), or the O_NDELAY option to
  5370.     open() or fcntl().  See also question 19.1.
  5371.  
  5372. 19.3:    How can I display a percentage-done indication that updates
  5373.     itself in place, or show one of those "twirling baton" progress
  5374.     indicators?
  5375.  
  5376. A:    These simple things, at least, you can do fairly portably.
  5377.     Printing the character '\r' will usually give you a carriage
  5378.     return without a line feed, so that you can overwrite the
  5379.     current line.  The character '\b' is a backspace, and will
  5380.     usually move the cursor one position to the left.
  5381.  
  5382.     References: ANSI Sec. 2.2.2; ISO Sec. 5.2.2.
  5383.  
  5384. 19.4:    How can I clear the screen?
  5385.     How can I print things in inverse video?
  5386.     How can I move the cursor to a specific x, y position?
  5387.  
  5388. A:    Such things depend on the terminal type (or display) you're
  5389.     using.  You will have to use a library such as termcap,
  5390.     terminfo, or curses, or some system-specific routines, to
  5391.     perform these operations.
  5392.  
  5393.     For clearing the screen, a halfway portable solution is to print
  5394.     a form-feed character ('\f'), which will cause some displays to
  5395.     clear.  Even more portable would be to print enough newlines to
  5396.     scroll everything away.  As a last resort, you could use
  5397.     system() (see question 19.27) to invoke an operating system
  5398.     clear-screen command.
  5399.  
  5400.     References: PCS Sec. 5.1.4 pp. 54-60, Sec. 5.1.5 pp. 60-62.
  5401.  
  5402. 19.5:    How do I read the arrow keys?  What about function keys?
  5403.  
  5404. A:    Terminfo, some versions of termcap, and some versions of curses
  5405.     have support for these non-ASCII keys.  Typically, a special key
  5406.     sends a multicharacter sequence (usually beginning with ESC,
  5407.     '\033'); parsing these can be tricky.  (curses will do the
  5408.     parsing for you, if you call keypad() first.)
  5409.  
  5410.     Under MS-DOS, if you receive a character with value 0 (*not*
  5411.     '0'!) while reading the keyboard, it's a flag indicating that
  5412.     the next character read will be a code indicating a special key.
  5413.     See any DOS programming guide for lists of keyboard codes.
  5414.     (Very briefly: the up, left, right, and down arrow keys are 72,
  5415.     75, 77, and 80, and the function keys are 59 through 68.)
  5416.  
  5417.     References: PCS Sec. 5.1.4 pp. 56-7.
  5418.  
  5419. 19.6:    How do I read the mouse?
  5420.  
  5421. A:    Consult your system documentation, or ask on an appropriate
  5422.     system-specific newsgroup (but check its FAQ list first).  Mouse
  5423.     handling is completely different under the X window system, MS-
  5424.     DOS, the Macintosh, and probably every other system.
  5425.  
  5426.     References: PCS Sec. 5.5 pp. 78-80.
  5427.  
  5428. 19.7:    How can I do serial ("comm") port I/O?
  5429.  
  5430. A:    It's system-dependent.  Under Unix, you typically open, read,
  5431.     and write a device file in /dev, and use the facilities of the
  5432.     terminal driver to adjust its characteristics.  (See also
  5433.     questions 19.1 and 19.2.)  Under MS-DOS, you can use the
  5434.     predefined stream stdaux, or a special file like COM1, or some
  5435.     primitive BIOS interrupts, or (if you require decent
  5436.     performance) any number of interrupt-driven serial I/O packages.
  5437.     Several netters recommend the book _C Programmer's Guide to
  5438.     Serial Communications_, by Joe Campbell.
  5439.  
  5440. 19.8:    How can I direct output to the printer?
  5441.  
  5442. A:    Under Unix, either use popen() (see question 19.30) to write to
  5443.     the lp or lpr program, or perhaps open a special file like
  5444.     /dev/lp.  Under MS-DOS, write to the (nonstandard) predefined
  5445.     stdio stream stdprn, or open the special files PRN or LPT1.
  5446.  
  5447.     References: PCS Sec. 5.3 pp. 72-74.
  5448.  
  5449. 19.9:    How do I send escape sequences to control a terminal or other
  5450.     device?
  5451.  
  5452. A:    If you can figure out how to send characters to the device at
  5453.     all (see question 19.8 above), it's easy enough to send escape
  5454.     sequences.  In ASCII, the ESC code is 033 (27 decimal), so code
  5455.     like
  5456.  
  5457.         fprintf(ofd, "\033[J");
  5458.  
  5459.     sends the sequence ESC [ J .
  5460.  
  5461. 19.10:    How can I do graphics?
  5462.  
  5463. A:    Once upon a time, Unix had a fairly nice little set of device-
  5464.     independent plot routines described in plot(3) and plot(5), but
  5465.     they've largely fallen into disuse.
  5466.  
  5467.     If you're programming for MS-DOS, you'll probably want to use
  5468.     libraries conforming to the VESA or BGI standards.
  5469.  
  5470.     If you're trying to talk to a particular plotter, making it draw
  5471.     is usually a matter of sending it the appropriate escape
  5472.     sequences; see also question 19.9.  The vendor may supply a C-
  5473.     callable library, or you may be able to find one on the net.
  5474.  
  5475.  
  5476.     If you're programming for a particular window system (Macintosh,
  5477.     X windows, Microsoft Windows), you will use its facilities; see
  5478.     the relevant documentation or newsgroup or FAQ list.
  5479.  
  5480.     References: PCS Sec. 5.4 pp. 75-77.
  5481.  
  5482. 19.11:    How can I check whether a file exists?  I want to warn the user
  5483.     if a requested input file is missing.
  5484.  
  5485. A:    It's surprisingly difficult to make this determination reliably
  5486.     and portably.  Any test you make can be invalidated if the file
  5487.     is created or deleted (i.e. by some other process) between the
  5488.     time you make the test and the time you try to open the file.
  5489.  
  5490.     Three possible test routines are stat(), access(), and fopen().
  5491.     (To make an approximate test for file existence with fopen(),
  5492.     just open for reading and close immediately.)  Of these, only
  5493.     fopen() is widely portable, and access(), where it exists, must
  5494.     be used carefully if the program uses the Unix set-UID feature.
  5495.  
  5496.     Rather than trying to predict in advance whether an operation
  5497.     such as opening a file will succeed, it's often better to try
  5498.     it, check the return value, and complain if it fails.
  5499.     (Obviously, this approach won't work if you're trying to avoid
  5500.     overwriting an existing file, unless you've got something like
  5501.     the O_EXCL file opening option available, which does just what
  5502.     you want in this case.)
  5503.  
  5504.     References: PCS Sec. 12 pp. 189,213; POSIX Sec. 5.3.1,
  5505.     Sec. 5.6.2, Sec. 5.6.3.
  5506.  
  5507. 19.12:    How can I find out the size of a file, prior to reading it in?
  5508.  
  5509. A:    If the "size of a file" is the number of characters you'll be
  5510.     able to read from it in C, it is difficult or impossible to
  5511.     determine this number exactly).
  5512.  
  5513.     Under Unix, the stat() call will give you an exact answer.
  5514.     Several other systems supply a Unix-like stat() which will give
  5515.     an approximate answer.  You can fseek() to the end and then use
  5516.     ftell(), but these tend to have the same problems: fstat() is
  5517.     not portable, and generally tells you the same thing stat()
  5518.     tells you; ftell() is not guaranteed to return a byte count
  5519.     except for binary files.  Some systems provide routines called
  5520.     filesize() or filelength(), but these are not portable, either.
  5521.  
  5522.     Are you sure you have to determine the file's size in advance?
  5523.     Since the most accurate way of determining the size of a file as
  5524.     a C program will see it is to open the file and read it, perhaps
  5525.     you can rearrange the code to learn the size as it reads.
  5526.  
  5527.     References: ANSI Sec. 4.9.9.4; ISO Sec. 7.9.9.4; H&S
  5528.     Sec. 15.5.1; PCS Sec. 12 p. 213; POSIX Sec. 5.6.2.
  5529.  
  5530. 19.13:    How can a file be shortened in-place without completely clearing
  5531.     or rewriting it?
  5532.  
  5533. A:    BSD systems provide ftruncate(), several others supply chsize(),
  5534.     and a few may provide a (possibly undocumented) fcntl option
  5535.     F_FREESP.  Under MS-DOS, you can sometimes use write(fd, "", 0).
  5536.     However, there is no portable solution, nor a way to delete
  5537.     blocks at the beginning.  See also question 19.14.
  5538.  
  5539. 19.14:    How can I insert or delete a line (or record) in the middle of a
  5540.     file?
  5541.  
  5542. A:    Short of rewriting the file, you probably can't.  The usual
  5543.     solution is simply to rewrite the file.  (Instead of deleting
  5544.     records, you might consider simply marking them as deleted, to
  5545.     avoid rewriting.)  See also questions 12.30 and 19.13.
  5546.  
  5547. 19.15:    How can I recover the file name given an open stream or file
  5548.     descriptor?
  5549.  
  5550. A:    This problem is, in general, insoluble.  Under Unix, for
  5551.     instance, a scan of the entire disk (perhaps involving special
  5552.     permissions) would theoretically be required, and would fail if
  5553.     the descriptor were connected to a pipe or referred to a deleted
  5554.     file (and could give a misleading answer for a file with
  5555.     multiple links).  It is best to remember the names of files
  5556.     yourself when you open them (perhaps with a wrapper function
  5557.     around fopen()).
  5558.  
  5559. 19.16:    How can I delete a file?
  5560.  
  5561. A:    The Standard C Library function is remove().  (This is therefore
  5562.     one of the few questions in this section for which the answer is
  5563.     *not* "It's system-dependent.")  On older, pre-ANSI Unix
  5564.     systems, remove() may not exist, in which case you can try
  5565.     unlink().
  5566.  
  5567.     References: K&R2 Sec. B1.1 p. 242; ANSI Sec. 4.9.4.1; ISO
  5568.     Sec. 7.9.4.1; H&S Sec. 15.15 p. 382; PCS Sec. 12 pp. 208,220-
  5569.     221; POSIX Sec. 5.5.1, Sec. 8.2.4.
  5570.  
  5571. 19.17:    Why can't I open a file by its explicit path?  The call
  5572.  
  5573.         fopen("c:\newdir\file.dat", "r")
  5574.  
  5575.     is failing.
  5576.  
  5577. A:    The file you actually requested -- with the characters \n and \f
  5578.     in its name -- probably doesn't exist, and isn't what you
  5579.     thought you were trying to open.
  5580.  
  5581.     In character constants and string literals, the backslash \ is
  5582.     an escape character, giving special meaning to the character
  5583.     following it.  In order for literal backslashes in a pathname to
  5584.     be passed through to fopen() (or any other routine) correctly,
  5585.     they have to be doubled, so that the first backslash in each
  5586.     pair quotes the second one:
  5587.  
  5588.         fopen("c:\\newdir\\file.dat", "r");
  5589.  
  5590.     Alternatively, under MS-DOS, it turns out that forward slashes
  5591.     are also accepted as directory separators, so you could use
  5592.  
  5593.         fopen("c:/newdir/file.dat", "r");
  5594.  
  5595.     (Note, by the way, that header file names mentioned in
  5596.     preprocessor #include directives are *not* string literals, so
  5597.     you may not have to worry about backslashes there.)
  5598.  
  5599. 19.18:    I'm getting an error, "Too many open files".  How can I increase
  5600.     the allowable number of simultaneously open files?
  5601.  
  5602. A:    There are actually at least two resource limitations on the
  5603.     number of simultaneously open files: the number of low-level
  5604.     "file descriptors" or "file handles" available in the operating
  5605.     system, and the number of FILE structures available in the stdio
  5606.     library.  Both must be sufficient.  Under MS-DOS systems, you
  5607.     can control the number of operating system file handles with a
  5608.     line in CONFIG.SYS.  Some compilers come with instructions (and
  5609.     perhaps a source file or two) for increasing the number of stdio
  5610.     FILE structures.
  5611.  
  5612. 19.20:    How can I read a directory in a C program?
  5613.  
  5614. A:    See if you can use the opendir() and readdir() routines, which
  5615.     are part of the POSIX standard and are available on most Unix
  5616.     variants.  Implementations also exist for MS-DOS, VMS, and other
  5617.     systems.  (MS-DOS also has FINDFIRST and FINDNEXT routines which
  5618.     do essentially the same thing.)  readdir() only returns file
  5619.     names; if you need more information about the file, try calling
  5620.     stat().  To match filenames to some wildcard pattern, see
  5621.     question 13.7.
  5622.  
  5623.     References: K&R2 Sec. 8.6 pp. 179-184; PCS Sec. 13 pp. 230-1;
  5624.     POSIX Sec. 5.1; Schumacher, ed., _Software Solutions in C_
  5625.     Sec. 8.
  5626.  
  5627. 19.22:    How can I find out how much memory is available?
  5628.  
  5629. A:    Your operating system may provide a routine which returns this
  5630.     information, but it's quite system-dependent.
  5631.  
  5632. 19.23:    How can I allocate arrays or structures bigger than 64K?
  5633.  
  5634. A:    A reasonable computer ought to give you transparent access to
  5635.     all available memory.  If you're not so lucky, you'll either
  5636.     have to rethink your program's use of memory, or use various
  5637.     system-specific techniques.
  5638.  
  5639.     64K is (still) a pretty big chunk of memory.  No matter how much
  5640.     memory your computer has available, it's asking a lot to be able
  5641.     to allocate huge amounts of it contiguously.  (The C Standard
  5642.     does not guarantee that a single object can be larger than 32K.)
  5643.     Often it's a good idea to use data structures which don't
  5644.     require that all memory be contiguous.  For dynamically-
  5645.     allocated multidimensional arrays, you can use pointers to
  5646.     pointers, as illustrated in question 6.16.  Instead of a large
  5647.     array of structures, you can use a linked list, or an array of
  5648.     pointers to structures.
  5649.  
  5650.     If you're using a PC-compatible (8086-based) system, and running
  5651.     up against a 640K limit, consider using "huge" memory model, or
  5652.     expanded or extended memory, or malloc variants such as halloc()
  5653.     or farmalloc(), or a 32-bit "flat" compiler (e.g. djgpp, see
  5654.     question 18.3), or some kind of a DOS extender, or another
  5655.     operating system.
  5656.  
  5657.     References: ANSI Sec. 2.2.4.1; ISO Sec. 5.2.4.1.
  5658.  
  5659. 19.24:    What does the error message "DGROUP data allocation exceeds 64K"
  5660.     mean, and what can I do about it?  I thought that using large
  5661.     model meant that I could use more than 64K of data!
  5662.  
  5663. A:    Even in large memory models, MS-DOS compilers apparently toss
  5664.     certain data (strings, some initialized global or static
  5665.     variables) into a default data segment, and it's this segment
  5666.     that is overflowing.  Either use less global data, or, if you're
  5667.     already limiting yourself to reasonable amounts (and if the
  5668.     problem is due to something like the number of strings), you may
  5669.     be able to coax the compiler into not using the default data
  5670.     segment for so much.  Some compilers place only "small" data
  5671.     objects in the default data segment, and give you a way (e.g.
  5672.     the /Gt option under Microsoft compilers) to configure the
  5673.     threshold for "small."
  5674.  
  5675. 19.25:    How can I access memory (a memory-mapped device, or graphics
  5676.     memory) located at a certain address?
  5677.  
  5678. A:    Set a pointer, of the appropriate type, to the right number
  5679.     (using an explicit cast to assure the compiler that you really
  5680.     do intend this nonportable conversion):
  5681.  
  5682.         unsigned int *magicloc = (unsigned int *)0x12345678;
  5683.  
  5684.     Then, *magicloc refers to the location you want.  (Under MS-DOS,
  5685.     you may find a macro like MK_FP() handy for working with
  5686.     segments and offsets.)
  5687.  
  5688.     References: K&R1 Sec. A14.4 p. 210; K&R2 Sec. A6.6 p. 199; ANSI
  5689.     Sec. 3.3.4; ISO Sec. 6.3.4; Rationale Sec. 3.3.4; H&S Sec. 6.2.7
  5690.     pp. 171-2.
  5691.  
  5692. 19.27:    How can I invoke another program (a standalone executable, or an
  5693.     operating system command) from within a C program?
  5694.  
  5695. A:    Use the library function system(), which does exactly that.
  5696.     Note that system's return value is the command's exit status,
  5697.     and usually has nothing to do with the output of the command.
  5698.     Note also that system() accepts a single string representing the
  5699.     command to be invoked; if you need to build up a complex command
  5700.     line, you can use sprintf().  See also question 19.30.
  5701.  
  5702.     References: K&R1 Sec. 7.9 p. 157; K&R2 Sec. 7.8.4 p. 167,
  5703.     Sec. B6 p. 253; ANSI Sec. 4.10.4.5; ISO Sec. 7.10.4.5; H&S
  5704.     Sec. 19.2 p. 407; PCS Sec. 11 p. 179.
  5705.  
  5706. 19.30:    How can I invoke another program or command and trap its output?
  5707.  
  5708. A:    Unix and some other systems provide a popen() routine, which
  5709.     sets up a stdio stream on a pipe connected to the process
  5710.     running a command, so that the output can be read (or the input
  5711.     supplied).  (Also, remember to call pclose().)
  5712.  
  5713.     If you can't use popen(), you may be able to use system(), with
  5714.     the output going to a file which you then open and read.
  5715.  
  5716.     If you're using Unix and popen() isn't sufficient, you can learn
  5717.     about pipe(), dup(), fork(), and exec().
  5718.  
  5719.     (One thing that probably would *not* work, by the way, would be
  5720.     to use freopen().)
  5721.  
  5722.     References: PCS Sec. 11 p. 169.
  5723.  
  5724. 19.31:    How can my program discover the complete pathname to the
  5725.     executable from which it was invoked?
  5726.  
  5727. A:    argv[0] may contain all or part of the pathname, or it may
  5728.     contain nothing.  You may be able to duplicate the command
  5729.     language interpreter's search path logic to locate the
  5730.     executable if the name in argv[0] is present but incomplete.
  5731.     However, there is no guaranteed solution.
  5732.  
  5733.     References: K&R1 Sec. 5.11 p. 111; K&R2 Sec. 5.10 p. 115; ANSI
  5734.     Sec. 2.1.2.2.1; ISO Sec. 5.1.2.2.1; H&S Sec. 20.1 p. 416.
  5735.  
  5736. 19.32:    How can I automatically locate a program's configuration files
  5737.     in the same directory as the executable?
  5738.  
  5739. A:    It's hard; see also question 19.31 above.  Even if you can
  5740.     figure out a workable way to do it, you might want to consider
  5741.     making the program's auxiliary (library) directory configurable,
  5742.     perhaps with an environment variable.  (It's especially
  5743.     important to allow variable placement of a program's
  5744.     configuration files when the program will be used by several
  5745.     people, e.g. on a multiuser system.)
  5746.  
  5747. 19.33:    How can a process change an environment variable in its caller?
  5748.  
  5749. A:    It may or may not be possible to do so at all.  Different
  5750.     operating systems implement global name/value functionality
  5751.     similar to the Unix environment in different ways.  Whether the
  5752.     "environment" can be usefully altered by a running program, and
  5753.     if so, how, is system-dependent.
  5754.  
  5755.     Under Unix, a process can modify its own environment (some
  5756.     systems provide setenv() or putenv() functions for the purpose),
  5757.     and the modified environment is generally passed on to child
  5758.     processes, but it is *not* propagated back to the parent
  5759.     process.
  5760.  
  5761. 19.36:    How can I read in an object file and jump to routines in it?
  5762.  
  5763. A:    You want a dynamic linker or loader.  It may be possible to
  5764.     malloc some space and read in object files, but you have to know
  5765.     an awful lot about object file formats, relocation, etc.  Under
  5766.     BSD Unix, you could use system() and ld -A to do the linking for
  5767.     you.  Many versions of SunOS and System V have the -ldl library
  5768.     which allows object files to be dynamically loaded.  Under VMS,
  5769.     use LIB$FIND_IMAGE_SYMBOL.  GNU has a package called "dld".  See
  5770.     also question 15.13.
  5771.  
  5772. 19.37:    How can I implement a delay, or time a user's response, with sub-
  5773.     second resolution?
  5774.  
  5775. A:    Unfortunately, there is no portable way.  V7 Unix, and derived
  5776.     systems, provided a fairly useful ftime() routine with
  5777.     resolution up to a millisecond, but it has disappeared from
  5778.     System V and POSIX.  Other routines you might look for on your
  5779.     system include clock(), delay(), gettimeofday(), msleep(),
  5780.     nap(), napms(), setitimer(), sleep(), times(), and usleep().
  5781.     (A routine called wait(), however, is at least under Unix *not*
  5782.     what you want.)  The select() and poll() calls (if available)
  5783.     can be pressed into service to implement simple delays.  On MS-
  5784.     DOS machines, it is possible to reprogram the system timer and
  5785.     timer interrupts.
  5786.  
  5787.     Of these, only clock() is part of the ANSI Standard.  The
  5788.     difference between two calls to clock() gives elapsed execution
  5789.     time, and if CLOCKS_PER_SEC is greater than 1, the difference will
  5790.     have subsecond resolution.  However, clock() gives elapsed
  5791.     processor time used by the current program, which on a
  5792.     multitasking system may differ considerably from real time.
  5793.  
  5794.     If you're trying to implement a delay and all you have available
  5795.     is a time-reporting function, you can implement a CPU-intensive
  5796.     busy-wait, but this is only an option on a single-user, single-
  5797.     tasking machine as it is terribly antisocial to any other
  5798.     processes.  Under a multi-tasking operating system, be sure to
  5799.     use a call which puts your process to sleep for the duration,
  5800.     such as sleep() or select(), or pause() in conjunction with
  5801.     alarm() or setitimer().
  5802.  
  5803.     For really brief delays, it's tempting to use a do-nothing loop
  5804.     like
  5805.  
  5806.         long int i;
  5807.         for(i = 0; i < 1000000; i++)
  5808.             ;
  5809.  
  5810.     but resist this temptation if at all possible!  For one thing,
  5811.     your carefully-calculated delay loops will stop working next
  5812.     month when a faster processor comes out.  Perhaps worse, a
  5813.     clever compiler may notice that the loop does nothing and
  5814.     optimize it away completely.
  5815.  
  5816.     References: H&S Sec. 18.1 pp. 398-9; PCS Sec. 12 pp. 197-8,215-
  5817.     6; POSIX Sec. 4.5.2.
  5818.  
  5819. 19.38:    How can I trap or ignore keyboard interrupts like control-C?
  5820.  
  5821. A:    The basic step is to call signal(), either as
  5822.  
  5823.         #include <signal.h>
  5824.         signal(SIGINT, SIG_IGN);
  5825.  
  5826.     to ignore the interrupt signal, or as
  5827.  
  5828.         extern void func(int);
  5829.         signal(SIGINT, func);
  5830.  
  5831.     to cause control to transfer to function func() on receipt of an
  5832.     interrupt signal.
  5833.  
  5834.     On a multi-tasking system such as Unix, it's best to use a
  5835.     slightly more involved technique:
  5836.  
  5837.         extern void func(int);
  5838.         if(signal(SIGINT, SIG_IGN) != SIG_IGN)
  5839.             signal(SIGINT, func);
  5840.  
  5841.     The test and extra call ensure that a keyboard interrupt typed
  5842.     in the foreground won't inadvertently interrupt a program
  5843.     running in the background (and it doesn't hurt to code calls to
  5844.     signal() this way on any system).
  5845.  
  5846.     On some systems, keyboard interrupt handling is also a function
  5847.     of the mode of the terminal-input subsystem; see question 19.1.
  5848.     On some systems, checking for keyboard interrupts is only
  5849.     performed when the program is reading input, and keyboard
  5850.     interrupt handling may therefore depend on which input routines
  5851.     are being called (and *whether* any input routines are active at
  5852.     all).  On MS-DOS systems, setcbrk() or ctrlbrk() functions may
  5853.     also be involved.
  5854.  
  5855.     References: ANSI Secs. 4.7,4.7.1; ISO Secs. 7.7,7.7.1; H&S
  5856.     Sec. 19.6 pp. 411-3; PCS Sec. 12 pp. 210-2; POSIX
  5857.     Secs. 3.3.1,3.3.4.
  5858.  
  5859. 19.39:    How can I handle floating-point exceptions gracefully?
  5860.  
  5861. A:    On many systems, you can define a routine matherr() which will
  5862.     be called when there are certain floating-point errors, such as
  5863.     errors in the math routines in <math.h>.  You may also be able
  5864.     to use signal() (see question 19.38 above) to catch SIGFPE.  See
  5865.     also question 14.9.
  5866.  
  5867.     References: Rationale Sec. 4.5.1.
  5868.  
  5869. 19.40:    How do I...  Use sockets?  Do networking?  Write client/server
  5870.     applications?
  5871.  
  5872. A:    All of these questions are outside of the scope of this list and
  5873.     have much more to do with the networking facilities which you
  5874.     have available than they do with C.  Good books on the subject
  5875.     are Douglas Comer's three-volume _Internetworking with TCP/IP_
  5876.     and W. R. Stevens's _UNIX Network Programming_.  (There is also
  5877.     plenty of information out on the net itself.)
  5878.  
  5879. 19.40b: How do I use BIOS calls?  How can I write ISR's?  How can I
  5880.     create TSR's?
  5881.  
  5882. A:    These are very particular to specific systems (PC compatibles
  5883.     running MS-DOS, most likely).  You'll get much better
  5884.     information in a specific newsgroup such as
  5885.     comp.os.msdos.programmer or its FAQ list; another excellent
  5886.     resource is Ralf Brown's interrupt list.
  5887.  
  5888. 19.41:    But I can't use all these nonstandard, system-dependent
  5889.     functions, because my program has to be ANSI compatible!
  5890.  
  5891. A:    You're out of luck.  Either you misunderstood your requirement,
  5892.     or it's an impossible one to meet.  ANSI/ISO Standard C simply
  5893.     does not define ways of doing these things.  (POSIX defines a
  5894.     few.)  It is possible, and desirable, for *most* of a program to
  5895.     be ANSI-compatible, deferring the system-dependent functionality
  5896.     to a few routines in a few files which are rewritten for each
  5897.     system ported to.
  5898.  
  5899.  
  5900. Section 20. Miscellaneous
  5901.  
  5902. 20.1:    How can I return multiple values from a function?
  5903.  
  5904. A:    Either pass pointers to several locations which the function can
  5905.     fill in, or have the function return a structure containing the
  5906.     desired values, or (in a pinch) consider global variables.  See
  5907.     also questions 2.7, 4.8, and 7.5.
  5908.  
  5909. 20.3:    How do I access command-line arguments?
  5910.  
  5911. A:    They are pointed to by the argv array with which main() is
  5912.     called.
  5913.  
  5914.     References: K&R1 Sec. 5.11 pp. 110-114; K&R2 Sec. 5.10 pp. 114-
  5915.     118; ANSI Sec. 2.1.2.2.1; ISO Sec. 5.1.2.2.1; H&S Sec. 20.1 p.
  5916.     416; PCS Sec. 5.6 pp. 81-2, Sec. 11 p. 159, pp. 339-40 Appendix
  5917.     F; Schumacher, ed., _Software Solutions in C_ Sec. 4 pp. 75-85.
  5918.  
  5919. 20.5:    How can I write data files which can be read on other machines
  5920.     with different word size, byte order, or floating point formats?
  5921.  
  5922. A:    The most portable solution is to use text files (usually ASCII),
  5923.     written with fprintf() and read with fscanf() or the like.
  5924.     (Similar advice also applies to network protocols.)  Be
  5925.     skeptical of arguments which imply that text files are too big,
  5926.     or that reading and writing them is too slow.  Not only is their
  5927.     efficiency frequently acceptable in practice, but the advantages
  5928.     of being able to interchange them easily between machines, and
  5929.     manipulate them with standard tools, can be overwhelming.
  5930.  
  5931.     If you must use a binary format, you can improve portability,
  5932.     and perhaps take advantage of prewritten I/O libraries, by
  5933.     making use of standardized formats such as Sun's XDR (RFC 1014),
  5934.     OSI's ASN.1 (referenced in CCITT X.409 and ISO 8825 "Basic
  5935.     Encoding Rules"), CDF, netCDF, or HDF.  See also questions 2.12
  5936.     and 12.38.
  5937.  
  5938.     References: PCS Sec. 6 pp. 86,88.
  5939.  
  5940. 20.6:    If I have a char * variable pointing to the name of a function,
  5941.     how can I call that function?
  5942.  
  5943. A:    The most straightforward thing to do is to maintain a
  5944.     correspondence table of names and function pointers:
  5945.  
  5946.         int func(), anotherfunc();
  5947.  
  5948.         struct { char *name; int (*funcptr)(); } symtab[] = {
  5949.             "func",        func,
  5950.             "anotherfunc",    anotherfunc,
  5951.         };
  5952.  
  5953.     Then, search the table for the name, and call via the associated
  5954.     function pointer.  See also questions 2.15 and 19.36.
  5955.  
  5956.     References: PCS Sec. 11 p. 168.
  5957.  
  5958. 20.8:    How can I implement sets or arrays of bits?
  5959.  
  5960. A:    Use arrays of char or int, with a few macros to access the
  5961.     desired bit at the proper index.  Here are some simple macros to
  5962.     use with arrays of char:
  5963.  
  5964.         #include <limits.h>        /* for CHAR_BIT */
  5965.  
  5966.         #define BITMASK(b) (1 << ((b) % CHAR_BIT))
  5967.         #define BITSLOT(b) ((b) / CHAR_BIT)
  5968.         #define BITSET(a, b) ((a)[BITSLOT(b)] |= BITMASK(b))
  5969.         #define BITTEST(a, b) ((a)[BITSLOT(b)] & BITMASK(b))
  5970.  
  5971.     (If you don't have <limits.h>, try using 8 for CHAR_BIT.)
  5972.  
  5973.     References: H&S Sec. 7.6.7 pp. 211-216.
  5974.  
  5975. 20.9:    How can I determine whether a machine's byte order is big-endian
  5976.     or little-endian?
  5977.  
  5978. A:    One way is to use a pointer:
  5979.  
  5980.         int x = 1;
  5981.         if(*(char *)&x == 1)
  5982.             printf("little-endian\n");
  5983.         else    printf("big-endian\n");
  5984.  
  5985.     It's also possible to use a union.
  5986.  
  5987.     See also question 10.16.
  5988.  
  5989.     References: H&S Sec. 6.1.2 pp. 163-4.
  5990.  
  5991. 20.10:    How can I convert integers to binary or hexadecimal?
  5992.  
  5993. A:    Make sure you really know what you're asking.  Integers are
  5994.     stored internally in binary, although for most purposes it is
  5995.     not incorrect to think of them as being in octal, decimal, or
  5996.     hexadecimal, whichever is convenient.  The base in which a
  5997.     number is expressed matters only when that number is read in
  5998.     from or written out to the outside world.
  5999.  
  6000.     In source code, a non-decimal base is indicated by a leading 0
  6001.     or 0x (for octal or hexadecimal, respectively).  During I/O, the
  6002.     base of a formatted number is controlled in the printf and scanf
  6003.     family of functions by the choice of format specifier (%d, %o,
  6004.     %x, etc.) and in the strtol() and strtoul() functions by the
  6005.     third argument.  During *binary* I/O, however, the base again
  6006.     becomes immaterial.
  6007.  
  6008.     For more information about "binary" I/O, see question 2.11.  See
  6009.     also questions 8.6 and 13.1.
  6010.  
  6011.     References: ANSI Secs. 4.10.1.5,4.10.1.6; ISO
  6012.     Secs. 7.10.1.5,7.10.1.6.
  6013.  
  6014. 20.11:    Can I use base-2 constants (something like 0b101010)?
  6015.     Is there a printf() format for binary?
  6016.  
  6017. A:    No, on both counts.  You can convert base-2 string
  6018.     representations to integers with strtol().
  6019.  
  6020. 20.12:    What is the most efficient way to count the number of bits which
  6021.     are set in a value?
  6022.  
  6023. A:    Many "bit-fiddling" problems like this one can be sped up and
  6024.     streamlined using lookup tables (but see question 20.13 below).
  6025.  
  6026. 20.13:    How can I make my code more efficient?
  6027.  
  6028. A:    Efficiency, though a favorite comp.lang.c topic, is not
  6029.     important nearly as often as people tend to think it is.  Most
  6030.     of the code in most programs is not time-critical.  When code is
  6031.     not time-critical, it is far more important that it be written
  6032.     clearly and portably than that it be written maximally
  6033.     efficiently.  (Remember that computers are very, very fast, and
  6034.     that even "inefficient" code can run without apparent delay.)
  6035.  
  6036.     It is notoriously difficult to predict what the "hot spots" in a
  6037.     program will be.  When efficiency is a concern, it is important
  6038.     to use profiling software to determine which parts of the
  6039.     program deserve attention.  Often, actual computation time is
  6040.     swamped by peripheral tasks such as I/O and memory allocation,
  6041.     which can be sped up by using buffering and caching techniques.
  6042.  
  6043.     Even for code that *is* time-critical, it is not as important to
  6044.     "microoptimize" the coding details.  Many of the "efficient
  6045.     coding tricks" which are frequently suggested (e.g. substituting
  6046.     shift operators for multiplication by powers of two) are
  6047.     performed automatically by even simpleminded compilers.
  6048.     Heavyhanded optimization attempts can make code so bulky that
  6049.     performance is actually degraded, and are rarely portable (i.e.
  6050.     they may speed things up on one machine but slow them down on
  6051.     another).  In any case, tweaking the coding usually results in
  6052.     at best linear performance improvements; the big payoffs are in
  6053.     better algorithms.
  6054.  
  6055.     For more discussion of efficiency tradeoffs, as well as good
  6056.     advice on how to improve efficiency when it is important, see
  6057.     chapter 7 of Kernighan and Plauger's _The Elements of
  6058.     Programming Style_, and Jon Bentley's _Writing Efficient
  6059.     Programs_.
  6060.  
  6061. 20.14:    Are pointers really faster than arrays?  How much do function
  6062.     calls slow things down?  Is ++i faster than i = i + 1?
  6063.  
  6064. A:    Precise answers to these and many similar questions depend of
  6065.     course on the processor and compiler in use.  If you simply must
  6066.     know, you'll have to time test programs carefully.  (Often the
  6067.     differences are so slight that hundreds of thousands of
  6068.     iterations are required even to see them.  Check the compiler's
  6069.     assembly language output, if available, to see if two purported
  6070.     alternatives aren't compiled identically.)
  6071.  
  6072.     It is "usually" faster to march through large arrays with
  6073.     pointers rather than array subscripts, but for some processors
  6074.     the reverse is true.
  6075.  
  6076.     Function calls, though obviously incrementally slower than in-
  6077.     line code, contribute so much to modularity and code clarity
  6078.     that there is rarely good reason to avoid them.
  6079.  
  6080.     Before rearranging expressions such as i = i + 1, remember that
  6081.     you are dealing with a compiler, not a keystroke-programmable
  6082.     calculator.  Any decent compiler will generate identical code
  6083.     for ++i, i += 1, and i = i + 1.  The reasons for using ++i or
  6084.     i += 1 over i = i + 1 have to do with style, not efficiency.
  6085.     (See also question 3.12.)
  6086.  
  6087. 20.17:    Is there a way to switch on strings?
  6088.  
  6089. A:    Not directly.  Sometimes, it's appropriate to use a separate
  6090.     function to map strings to integer codes, and then switch on
  6091.     those.  Otherwise, of course, you can fall back on strcmp() and
  6092.     a conventional if/else chain.  See also questions 10.12, 20.18,
  6093.     and 20.29.
  6094.  
  6095.     References: K&R1 Sec. 3.4 p. 55; K&R2 Sec. 3.4 p. 58; ANSI
  6096.     Sec. 3.6.4.2; ISO Sec. 6.6.4.2; H&S Sec. 8.7 p. 248.
  6097.  
  6098. 20.18:    Is there a way to have non-constant case labels (i.e. ranges or
  6099.     arbitrary expressions)?
  6100.  
  6101. A:    No.  The switch statement was originally designed to be quite
  6102.     simple for the compiler to translate, therefore case labels are
  6103.     limited to single, constant, integral expressions.  You *can*
  6104.     attach several case labels to the same statement, which will let
  6105.     you cover a small range if you don't mind listing all cases
  6106.     explicitly.
  6107.  
  6108.     If you want to select on arbitrary ranges or non-constant
  6109.     expressions, you'll have to use an if/else chain.
  6110.  
  6111.     See also questions question 20.17.
  6112.  
  6113.     References: K&R1 Sec. 3.4 p. 55; K&R2 Sec. 3.4 p. 58; ANSI
  6114.     Sec. 3.6.4.2; ISO Sec. 6.6.4.2; Rationale Sec. 3.6.4.2; H&S
  6115.     Sec. 8.7 p. 248.
  6116.  
  6117. 20.19:    Are the outer parentheses in return statements really optional?
  6118.  
  6119. A:    Yes.
  6120.  
  6121.     Long ago, in the early days of C, they were required, and just
  6122.     enough people learned C then, and wrote code which is still in
  6123.     circulation, that the notion that they might still be required
  6124.     is widespread.
  6125.  
  6126.     (As it happens, parentheses are optional with the sizeof
  6127.     operator, too, as long as its operand is a variable or a unary
  6128.     expression.)
  6129.  
  6130.     References: K&R1 Sec. A18.3 p. 218; ANSI Sec. 3.3.3, Sec. 3.6.6;
  6131.     ISO Sec. 6.3.3, Sec. 6.6.6; H&S Sec. 8.9 p. 254.
  6132.  
  6133. 20.20:    Why don't C comments nest?  How am I supposed to comment out
  6134.     code containing comments?  Are comments legal inside quoted
  6135.     strings?
  6136.  
  6137. A:    C comments don't nest mostly because PL/I's comments, which C's
  6138.     are borrowed from, don't either.  Therefore, it is usually
  6139.     better to "comment out" large sections of code, which might
  6140.     contain comments, with #ifdef or #if 0 (but see question 11.19).
  6141.  
  6142.     The character sequences /* and */ are not special within double-
  6143.     quoted strings, and do not therefore introduce comments, because
  6144.     a program (particularly one which is generating C code as
  6145.     output) might want to print them.
  6146.  
  6147.     Note also that // comments, as in C++, are not currently legal
  6148.     in C, so it's not a good idea to use them in C programs (even if
  6149.     your compiler supports them as an extension).
  6150.  
  6151.     References: K&R1 Sec. A2.1 p. 179; K&R2 Sec. A2.2 p. 192; ANSI
  6152.     Sec. 3.1.9 (esp. footnote 26), Appendix E; ISO Sec. 6.1.9, Annex
  6153.     F; Rationale Sec. 3.1.9; H&S Sec. 2.2 pp. 18-9; PCS Sec. 10 p.
  6154.     130.
  6155.  
  6156. 20.24:    Why doesn't C have nested functions?
  6157.  
  6158. A:    It's not trivial to implement nested functions such that they
  6159.     have the proper access to local variables in the containing
  6160.     function(s), so they were deliberately left out of C as a
  6161.     simplification.  (gcc does allow them, as an extension.)  For
  6162.     many potential uses of nested functions (e.g. qsort comparison
  6163.     functions), an adequate if slightly cumbersome solution is to
  6164.     use an adjacent function with static declaration, communicating
  6165.     if necessary via a few static variables.  (A cleaner solution
  6166.     when such functions must communicate is to pass around a pointer
  6167.     to a structure containing the necessary context.)
  6168.  
  6169. 20.25:    How can I call FORTRAN (C++, BASIC, Pascal, Ada, LISP) functions
  6170.     from C?  (And vice versa?)
  6171.  
  6172. A:    The answer is entirely dependent on the machine and the specific
  6173.     calling sequences of the various compilers in use, and may not
  6174.     be possible at all.  Read your compiler documentation very
  6175.     carefully; sometimes there is a "mixed-language programming
  6176.     guide," although the techniques for passing arguments and
  6177.     ensuring correct run-time startup are often arcane.  More
  6178.     information may be found in FORT.gz by Glenn Geers, available
  6179.     via anonymous ftp from suphys.physics.su.oz.au in the src
  6180.     directory.
  6181.  
  6182.     cfortran.h, a C header file, simplifies C/FORTRAN interfacing on
  6183.     many popular machines.  It is available via anonymous ftp from
  6184.     zebra.desy.de (131.169.2.244).
  6185.  
  6186.     In C++, a "C" modifier in an external function declaration
  6187.     indicates that the function is to be called using C calling
  6188.     conventions.
  6189.  
  6190.     References: H&S Sec. 4.9.8 pp. 106-7.
  6191.  
  6192. 20.26:    Does anyone know of a program for converting Pascal or FORTRAN
  6193.     (or LISP, Ada, awk, "Old" C, ...) to C?
  6194.  
  6195. A:    Several freely distributable programs are available:
  6196.  
  6197.     p2c    A Pascal to C converter written by Dave Gillespie,
  6198.         posted to comp.sources.unix in March, 1990 (Volume 21);
  6199.         also available by anonymous ftp from
  6200.         csvax.cs.caltech.edu, file pub/p2c-1.20.tar.Z .
  6201.  
  6202.     ptoc    Another Pascal to C converter, this one written in
  6203.         Pascal (comp.sources.unix, Volume 10, also patches in
  6204.         Volume 13?).
  6205.  
  6206.     f2c    A Fortran to C converter jointly developed by people
  6207.         from Bell Labs, Bellcore, and Carnegie Mellon.  To find
  6208.         out more about f2c, send the mail message "send index
  6209.         from f2c" to netlib@research.att.com or research!netlib.
  6210.         (It is also available via anonymous ftp on
  6211.         netlib.att.com, in directory netlib/f2c.)
  6212.  
  6213.     This FAQ list's maintainer also has available a list of a few
  6214.     other commercial translation products, and some for more obscure
  6215.     languages.
  6216.  
  6217.     See also questions 11.31 and 18.16.
  6218.  
  6219. 20.27:    Is C++ a superset of C?  Can I use a C++ compiler to compile C
  6220.     code?
  6221.  
  6222. A:    C++ was derived from C, and is largely based on it, but there
  6223.     are some legal C constructs which are not legal C++.
  6224.     Conversely, ANSI C inherited several features from C++,
  6225.     including prototypes and const, so neither language is really a
  6226.     subset or superset of the other.  In spite of the differences,
  6227.     many C programs will compile correctly in a C++ environment, and
  6228.     many recent compilers offer both C and C++ compilation modes.
  6229.  
  6230.     References: H&S p. xviii, Sec. 1.1.5 p. 6, Sec. 2.8 pp. 36-7,
  6231.     Sec. 4.9 pp. 104-107.
  6232.  
  6233. 20.28:    I need a sort of an "approximate" strcmp routine, for comparing
  6234.     two strings for close, but not necessarily exact, equality.
  6235.  
  6236. A:    Some nice information and algorithms having to do with
  6237.     approximate string matching, as well as a useful bibliography,
  6238.     can be found in Sun Wu and Udi Manber's paper "AGREP -- A Fast
  6239.     Approximate Pattern-Matching Tool."
  6240.  
  6241.     Another approach involves the "soundex" algorithm, which maps
  6242.     similar-sounding words to the same codes.  Soundex was designed
  6243.     for discovering similar-sounding names (for telephone directory
  6244.     assistance, as it happens), but it can be pressed into service
  6245.     for processing arbitrary words.
  6246.  
  6247.     References: Knuth Sec. 6 pp. 391-2 Volume 3; Wu and Manber,
  6248.     "AGREP -- A Fast Approximate Pattern-Matching Tool" .
  6249.  
  6250. 20.29:    What is hashing?
  6251.  
  6252. A:    Hashing is the process of mapping strings to integers, usually
  6253.     in a relatively small range.  A "hash function" maps a string
  6254.     (or some other data structure) to a a bounded number (the "hash
  6255.     bucket") which can more easily be used as an index in an array,
  6256.     or for performing repeated comparisons.  (Obviously, a mapping
  6257.     from a potentially huge set of strings to a small set of
  6258.     integers will not be unique.  Any algorithm using hashing
  6259.     therefore has to deal with the possibility of "collisions.")
  6260.     Many hashing functions and related algorithms have been
  6261.     developed; a full treatment is beyond the scope of this list.
  6262.  
  6263.     References: K&R2 Sec. 6.6; Knuth Sec. 6.4 pp. 506-549 Volume 3;
  6264.     Sedgewick Sec. 16 pp. 231-244.
  6265.  
  6266. 20.31:    How can I find the day of the week given the date?
  6267.  
  6268. A:    Use mktime() or localtime() (see questions 13.13 and 13.14, but
  6269.     beware of DST adjustments if tm_hour is 0), or Zeller's
  6270.     congruence (see the sci.math FAQ list), or this elegant code by
  6271.     Tomohiko Sakamoto:
  6272.  
  6273.         dayofweek(y, m, d)    /* 0 = Sunday */
  6274.         int y, m, d;        /* 1 <= m <= 12, y > 1752 or so */
  6275.         {
  6276.             static int t[] = {0, 3, 2, 5, 0, 3, 5, 1, 4, 6, 2, 4};
  6277.             y -= m < 3;
  6278.             return (y + y/4 - y/100 + y/400 + t[m-1] + d) % 7;
  6279.         }
  6280.  
  6281.     See also questions 13.14 and 20.32.
  6282.  
  6283.     References: ANSI Sec. 4.12.2.3; ISO Sec. 7.12.2.3.
  6284.  
  6285. 20.32:    Will 2000 be a leap year?  Is (year % 4 == 0) an accurate test
  6286.     for leap years?
  6287.  
  6288. A:    Yes and no, respectively.  The full expression for the present
  6289.     Gregorian calendar is
  6290.  
  6291.         year % 4 == 0 && (year % 100 != 0 || year % 400 == 0)
  6292.  
  6293.     See a good astronomical almanac or other reference for details.
  6294.     (To forestall an eternal debate: references which claim the
  6295.     existence of a 4000-year rule are wrong.)
  6296.  
  6297. 20.34:    Here's a good puzzle: how do you write a program which produces
  6298.     its own source code as its output?
  6299.  
  6300. A:    It is actually quite difficult to write a self-reproducing
  6301.     program that is truly portable, due particularly to quoting and
  6302.     character set difficulties.
  6303.  
  6304.     Here is a classic example (which is normally presented on one
  6305.     line, although it will "fix" itself the first time it's run):
  6306.  
  6307.         char*s="char*s=%c%s%c;main(){printf(s,34,s,34);}";
  6308.         main(){printf(s,34,s,34);}
  6309.  
  6310.     (This program, like many of the genre, assumes that the double-
  6311.     quote character " has the value 34, as it does in ASCII.)
  6312.  
  6313. 20.35:    What is "Duff's Device"?
  6314.  
  6315. A:    It's a devastatingly deviously unrolled byte-copying loop,
  6316.     devised by Tom Duff while he was at Lucasfilm.  In its "classic"
  6317.     form, it looks like:
  6318.  
  6319.         register n = (count + 7) / 8;    /* count > 0 assumed */
  6320.         switch (count % 8)
  6321.         {
  6322.         case 0:    do { *to = *from++;
  6323.         case 7:        *to = *from++;
  6324.         case 6:         *to = *from++;
  6325.         case 5:        *to = *from++;
  6326.         case 4:        *to = *from++;
  6327.         case 3:        *to = *from++;
  6328.         case 2:        *to = *from++;
  6329.         case 1:        *to = *from++;
  6330.                    } while (--n > 0);
  6331.         }
  6332.  
  6333.     where count bytes are to be copied from the array pointed to by
  6334.     from to the memory location pointed to by to (which is a memory-
  6335.     mapped device output register, which is why to isn't
  6336.     incremented).  It solves the problem of handling the leftover
  6337.     bytes (when count isn't a multiple of 8) by interleaving a
  6338.     switch statement with the loop which copies bytes 8 at a time.
  6339.     (Believe it or not, it *is* legal to have case labels buried
  6340.     within blocks nested in a switch statement like this.  In his
  6341.     announcement of the technique to C's developers and the world,
  6342.     Duff noted that C's switch syntax, in particular its "fall
  6343.     through" behavior, had long been controversial, and that "This
  6344.     code forms some sort of argument in that debate, but I'm not
  6345.     sure whether it's for or against.")
  6346.  
  6347. 20.36:    When will the next International Obfuscated C Code Contest
  6348.     (IOCCC) be held?  How can I get a copy of the current and
  6349.     previous winning entries?
  6350.  
  6351. A:    The contest schedule is tied to the dates of the USENIX
  6352.     conferences at which the winners are announced.  At the time of
  6353.     this writing, it is expected that the yearly contest will open
  6354.     in October.  To obtain a current copy of the rules and
  6355.     guidelines, send e-mail with the Subject: line "send rules" to:
  6356.  
  6357.         {apple,pyramid,sun,uunet}!hoptoad!judges  or
  6358.         judges@toad.com
  6359.  
  6360.     (Note that these are *not* the addresses for submitting
  6361.     entries.)
  6362.  
  6363.     Contest winners should be announced at the winter USENIX
  6364.     conference in January, and are posted to the net sometime
  6365.     thereafter.  Winning entries from previous years (back to 1984)
  6366.     are archived at ftp.uu.net (see question 18.16) under the
  6367.     directory pub/ioccc/.
  6368.  
  6369.     As a last resort, previous winners may be obtained by sending e-
  6370.     mail to the above address, using the Subject: "send YEAR
  6371.     winners", where YEAR is a single four-digit year, a year range,
  6372.     or "all".
  6373.  
  6374. 20.37:    What was the entry keyword mentioned in K&R1?
  6375.  
  6376. A:    It was reserved to allow the possibility of having functions
  6377.     with multiple, differently-named entry points, a la FORTRAN.  It
  6378.     was not, to anyone's knowledge, ever implemented (nor does
  6379.     anyone remember what sort of syntax might have been imagined for
  6380.     it).  It has been withdrawn, and is not a keyword in ANSI C.
  6381.     (See also question 1.12.)
  6382.  
  6383.     References: K&R2 p. 259 Appendix C.
  6384.  
  6385. 20.38:    Where does the name "C" come from, anyway?
  6386.  
  6387. A:    C was derived from Ken Thompson's experimental language B, which
  6388.     was inspired by Martin Richards's BCPL (Basic Combined
  6389.     Programming Language), which was a simplification of CPL
  6390.     (Cambridge Programming Language).  For a while, there was
  6391.     speculation that C's successor might be named P (the third
  6392.     letter in BCPL) instead of D, but of course the most visible
  6393.     descendant language today is C++.
  6394.  
  6395. 20.39:    How do you pronounce "char"?
  6396.  
  6397. A:    You can pronounce the C keyword "char" in at least three ways:
  6398.     like the English words "char," "care," or "car;" the choice is
  6399.     arbitrary.
  6400.  
  6401. 20.40:    Where can I get extra copies of this list?  What about back
  6402.     issues?
  6403.  
  6404. A:    An up-to-date copy may be obtained from ftp.eskimo.com in
  6405.     directory u/s/scs/C-faq/.  You can also just pull it off the
  6406.     net; it is normally posted to comp.lang.c on the first of each
  6407.     month, with an Expires: line which should keep it around all
  6408.     month.  A parallel, abridged version is available (and posted),
  6409.     as is a list of changes accompanying each significantly updated
  6410.     version.
  6411.  
  6412.     The various versions of this list are also posted to the
  6413.     newsgroups comp.answers and news.answers .  Several sites
  6414.     archive news.answers postings and other FAQ lists, including
  6415.     this one; two sites are rtfm.mit.edu (directories
  6416.     pub/usenet/news.answers/C-faq/ and pub/usenet/comp.lang.c/) and
  6417.     ftp.uu.net (directory usenet/news.answers/C-faq/).  An archie
  6418.     server (see question 18.16) should help you find others; ask it
  6419.     to "find C-faq".  If you don't have ftp access, a mailserver at
  6420.     rtfm.mit.edu can mail you FAQ lists: send a message containing
  6421.     the single word help to mail-server@rtfm.mit.edu .  See the meta-
  6422.     FAQ list in news.answers for more information.
  6423.  
  6424.     A hypertext (HTML) version of this FAQ list is available on the
  6425.     World-Wide Web; the URL is http://www.eskimo.com/~scs/C-faq/top.html .
  6426.     URL's pointing at all FAQ lists (these may also allow topic
  6427.     searching) are http://www.cis.ohio-
  6428.     state.edu/hypertext/faq/usenet/FAQ-List.html and
  6429.     http://www.luth.se/wais/ .
  6430.  
  6431.     An extended version of this FAQ list is being published by
  6432.     Addison-Wesley as _C Programming FAQs: Frequently Asked
  6433.     Questions_ (ISBN 0-201-84519-9).  It should be available in
  6434.     November 1995.
  6435.  
  6436.     This list is an evolving document of questions which have been
  6437.     Frequent since before the Great Renaming, not just a collection
  6438.     of this month's interesting questions.  Older copies are
  6439.     obsolete and don't contain much, except the occasional typo,
  6440.     that the current list doesn't.
  6441.  
  6442.  
  6443. Bibliography
  6444.  
  6445. Americal National Standards Institute, _American National Standard for
  6446. Information Systems -- Programming Language -- C_, ANSI X3.159-1989 (see
  6447. question 11.2).  [ANSI]
  6448.  
  6449. Americal National Standards Institute, _Rationale for American National
  6450. Standard for Information Systems -- Programming Language -- C_ (see
  6451. question 11.2).  [Rationale]
  6452.  
  6453. Jon Bentley, _Writing Efficient Programs_, Prentice-Hall, 1982, ISBN 0-
  6454. 13-970244-X.
  6455.  
  6456. G.E.P. Box and Mervin E. Muller, "A Note on the Generation of Random
  6457. Normal Deviates," _Annals of Mathematical Statistics_, Vol. 29 #2, June,
  6458. 1958, pp. 610-611.
  6459.  
  6460. David Burki, "Date Conversions," _The C Users Journal_, February 1993,
  6461. pp. 29-34.
  6462.  
  6463. Ian F. Darwin, _Checking C Programs with lint_, O'Reilly, 1988, ISBN 0-
  6464. 937175-30-7.
  6465.  
  6466. David Goldberg, "What Every Computer Scientist Should Know about
  6467. Floating-Point Arithmetic," _ACM Computing Surveys_, Vol. 23 #1, March,
  6468. 1991, pp. 5-48.
  6469.  
  6470. Samuel P. Harbison and Guy L. Steele, Jr., _C: A Reference Manual_,
  6471. Fourth Edition, Prentice-Hall, 1995, ISBN 0-13-326224-3.  [H&S]
  6472.  
  6473. Mark R. Horton, _Portable C Software_, Prentice Hall, 1990, ISBN 0-13-
  6474. 868050-7.  [PCS]
  6475.  
  6476. Institute of Electrical and Electronics Engineers, _Portable Operating
  6477. System Interface (POSIX) -- Part 1: System Application Program Interface
  6478. (API) [C Language_, IEEE Std. 1003.1, ISO/IEC 9945-1.
  6479.  
  6480. International Organization for Standardization, ISO 9899:1990 (see
  6481. question 11.2).  [ISO]
  6482.  
  6483. Brian W. Kernighan and P.J. Plauger, _The Elements of Programming
  6484. Style_, Second Edition, McGraw-Hill, 1978, ISBN 0-07-034207-5.
  6485.  
  6486. Brian W. Kernighan and Dennis M. Ritchie, _The C Programming Language_,
  6487. Prentice-Hall, 1978, ISBN 0-13-110163-3.  [K&R1]
  6488.  
  6489. Brian W. Kernighan and Dennis M. Ritchie, _The C Programming Language_,
  6490. Second Edition, Prentice Hall, 1988, ISBN 0-13-110362-8, 0-13-110370-9.
  6491. [K&R2]
  6492.  
  6493. Donald E. Knuth, _The Art of Computer Programming_.  Volume 1:
  6494. _Fundamental Algorithms_, Second Edition, Addison-Wesley, 1973, ISBN 0-
  6495. 201-03809-9.  Volume 2: _Seminumerical Algorithms_, Second Edition,
  6496. Addison-Wesley, 1981, ISBN 0-201-03822-6.  Volume 3: _Sorting and
  6497. Searching_, Addison-Wesley, 1973, ISBN 0-201-03803-X.  [Knuth]
  6498.  
  6499. Andrew Koenig, _C Traps and Pitfalls_, Addison-Wesley, 1989, ISBN 0-201-
  6500. 17928-8.  [CT&P]
  6501.  
  6502. Stephen K. Park and Keith W. Miller, "Random Number Generators: Good
  6503. Ones are Hard to Find," _Communications of the ACM_, Vol. 31 #10,
  6504. October, 1988, pp. 1192-1201 (also technical correspondence August,
  6505. 1989, pp. 1020-1024, and July, 1993, pp. 108-110).
  6506.  
  6507. P.J. Plauger, _The Standard C Library_, Prentice Hall, 1992, ISBN 0-13-
  6508. 131509-9.
  6509.  
  6510. Thomas Plum, _C Programming Guidelines_, Second Edition, Plum Hall,
  6511. 1989, ISBN 0-911537-07-4.
  6512.  
  6513. William H. Press, Saul A. Teukolsky, William T. Vetterling, and Brian P.
  6514. Flannery, _Numerical Recipes in C_, Second Edition, Cambridge University
  6515. Press, 1992, ISBN 0-521-43108-5.
  6516.  
  6517. Dale Schumacher, Ed., _Software Solutions in C_, AP Professional, 1994,
  6518. ISBN 0-12-632360-7.
  6519.  
  6520. Robert Sedgewick, _Algorithms in C_, Addison-Wesley, 1990, ISBN 0-201-
  6521. 51425-7.
  6522.  
  6523. Charles Simonyi and Martin Heller, "The Hungarian Revolution," _Byte_,
  6524. August, 1991, pp.131-138.
  6525.  
  6526. David Straker, _C Style: Standards and Guidelines_, Prentice Hall, ISBN
  6527. 0-13-116898-3.
  6528.  
  6529. Steve Summit, _C Programming FAQs: Frequently Asked Questions_, Addison-
  6530. Wesley, 1995, ISBN 0-201-84519-9.  [The book version of this FAQ list.]
  6531.  
  6532. Sun Wu and Udi Manber, "AGREP -- A Fast Approximate Pattern-Matching
  6533. Tool," USENIX Conference Proceedings, Winter, 1992, pp. 153-162.
  6534.  
  6535. There is another bibliography in the revised Indian Hill style guide
  6536. (see question 17.9).  See also question 18.10.
  6537.  
  6538.  
  6539. Acknowledgements
  6540.  
  6541. Thanks to Jamshid Afshar, David Anderson, Tanner Andrews, Sudheer Apte,
  6542. Joseph Arceneaux, Randall Atkinson, Rick Beem, Peter Bennett, Wayne
  6543. Berke, Dan Bernstein, Tanmoy Bhattacharya, John Bickers, Gary Blaine,
  6544. Yuan Bo, Dave Boutcher, Michael Bresnahan, Vincent Broman, Stan Brown,
  6545. Joe Buehler, Kimberley Burchett, Gordon Burditt, Burkhard Burow, Conor
  6546. P. Cahill, D'Arcy J.M. Cain, Christopher Calabrese, Ian Cargill, Vinit
  6547. Carpenter, Paul Carter, Mike Chambers, Billy Chambless, Franklin Chen,
  6548. Jonathan Chen, Raymond Chen, Richard Cheung, Steve Clamage, Ken Corbin,
  6549. Ian Cottam, Russ Cox, Jonathan Coxhead, Lee Crawford, Steve Dahmer,
  6550. Andrew Daviel, James Davies, John E. Davis, Ken Delong,
  6551. Norm Diamond, Jeff Dunlop, Ray Dunn, Stephen M. Dunn, Michael J. Eager,
  6552. Scott Ehrlich, Arno Eigenwillig, Dave Eisen, Bjorn Engsig, David Evans,
  6553. Clive D.W. Feather, Dominic Feeley, Simao Ferraz, Chris Flatters, Rod
  6554. Flores, Alexander Forst, Steve Fosdick, Jeff Francis, Tom Gambill, Dave
  6555. Gillespie, Samuel Goldstein, Tim Goodwin, Alasdair Grant, Ron Guilmette,
  6556. Doug Gwyn, Michael Hafner, Tony Hansen, Elliotte Rusty Harold, Joe
  6557. Harrington, Des Herriott, Guy Harris, John Hascall, Ger Hobbelt, Jos
  6558. Horsmeier, Blair Houghton, James C. Hu, Chin Huang, David Hurt, Einar
  6559. Indridason, Vladimir Ivanovic, Jon Jagger, Ke Jin, Kirk Johnson, Larry
  6560. Jones, Arjan Kenter, James Kew, Lawrence Kirby, Kin-ichi Kitano, Peter
  6561. Klausler, Andrew Koenig, Tom Koenig, Adam Kolawa, Jukka Korpela, Ajoy
  6562. Krishnan T, Markus Kuhn, Deepak Kulkarni, Oliver Laumann, John Lauro,
  6563. Felix Lee, Mike Lee, Timothy J. Lee, Tony Lee, Marty Leisner, Don Libes,
  6564. Brian Liedtke, Philip Lijnzaad, Keith Lindsay, Yen-Wei Liu, Paul Long,
  6565. Christopher Lott, Tim Love, Tim McDaniel, Kevin McMahon, Stuart
  6566. MacMartin, John R. MacMillan, Andrew Main, Bob Makowski, Evan Manning,
  6567. Barry Margolin, George Matas, Brad Mears, Roger Miller, Bill Mitchell,
  6568. Mark Moraes, Darren Morby, Bernhard Muenzer, David Murphy, Walter
  6569. Murray, Ralf Muschall, Ken Nakata, Todd Nathan, Landon Curt Noll, Tim
  6570. Norman, Paul Nulsen, David O'Brien, Richard A. O'Keefe, Adam Kolawa,
  6571. James Ojaste, Hans Olsson, Bob Peck, Andrew Phillips, Christopher
  6572. Phillips, Francois Pinard, Nick Pitfield, Wayne Pollock, Dan Pop, Lutz
  6573. Prechelt, Lynn Pye, Kevin D. Quitt, Pat Rankin, Arjun Ray, Eric S.
  6574. Raymond, Peter W. Richards, Eric Roode, Manfred Rosenboom, J. M.
  6575. Rosenstock, Rick Rowe, Erkki Ruohtula, John Rushford, Kadda Sahnine,
  6576. Tomohiko Sakamoto, Matthew Saltzman, Rich Salz, Chip Salzenberg, Matthew
  6577. Sams, Paul Sand, DaviD W. Sanderson, Frank Sandy, Christopher Sawtell,
  6578. Jonas Schlein, Paul Schlyter, Doug Schmidt, Rene Schmit, Russell Schulz,
  6579. Dean Schulze, Chris Sears, Patricia Shanahan, Raymond Shwake, Peter da
  6580. Silva, Joshua Simons, Ross Smith, Henri Socha, Leslie J. Somos, Henry
  6581. Spencer, David Spuler, James Stern, Bob Stout, Steve Sullivan, Melanie
  6582. Summit, Erik Talvola, Dave Taylor, Clarke Thatcher, Wayne Throop, Chris
  6583. Torek, Steve Traugott, Ilya Tsindlekht, Andrew Tucker, Goran Uddeborg,
  6584. Rodrigo Vanegas, Jim Van Zandt, Wietse Venema, Tom Verhoeff, Ed
  6585. Vielmetti, Larry Virden, Chris Volpe, Mark Warren, Alan Watson, Kurt
  6586. Watzka, Larry Weiss, Martin Weitzel, Howard West, Tom White, Freek
  6587. Wiedijk, Dik T. Winter, Lars Wirzenius, Dave Wolverton, Mitch Wright,
  6588. Conway Yee, Ozan S. Yigit, and Zhuo Zang, who have contributed, directly
  6589. or indirectly, to this article.  Special thanks to Karl Heuer, Jutta
  6590. Degener, and particularly to Mark Brader, who (to borrow a line from
  6591. Steve Johnson) have goaded me beyond my inclination, and occasionally
  6592. beyond my endurance, in relentless pursuit of a better FAQ list.
  6593.  
  6594.                     Steve Summit
  6595.                     scs@eskimo.com
  6596.  
  6597. This article is Copyright 1990-1996 by Steve Summit.
  6598. Content from the book _C Programming FAQs: Frequently Asked Questions_
  6599. is made available here by permission of the author and the publisher as
  6600. a service to the community.  It is intended to complement the use of the
  6601. published text and is protected by international copyright laws.  The
  6602. content is made available here and may be accessed freely for personal
  6603. use but may not be republished without permission.
  6604.